Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * sequence.c
4 : : * PostgreSQL sequences support code.
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/commands/sequence.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : #include "postgres.h"
16 : :
17 : : #include "access/htup_details.h"
18 : : #include "access/multixact.h"
19 : : #include "access/relation.h"
20 : : #include "access/sequence.h"
21 : : #include "access/table.h"
22 : : #include "access/transam.h"
23 : : #include "access/xact.h"
24 : : #include "access/xloginsert.h"
25 : : #include "catalog/dependency.h"
26 : : #include "catalog/indexing.h"
27 : : #include "catalog/namespace.h"
28 : : #include "catalog/objectaccess.h"
29 : : #include "catalog/pg_sequence.h"
30 : : #include "catalog/pg_type.h"
31 : : #include "catalog/storage_xlog.h"
32 : : #include "commands/defrem.h"
33 : : #include "commands/sequence.h"
34 : : #include "commands/sequence_xlog.h"
35 : : #include "commands/tablecmds.h"
36 : : #include "funcapi.h"
37 : : #include "miscadmin.h"
38 : : #include "nodes/makefuncs.h"
39 : : #include "parser/parse_type.h"
40 : : #include "storage/bufmgr.h"
41 : : #include "storage/lmgr.h"
42 : : #include "storage/proc.h"
43 : : #include "storage/smgr.h"
44 : : #include "utils/acl.h"
45 : : #include "utils/builtins.h"
46 : : #include "utils/lsyscache.h"
47 : : #include "utils/pg_lsn.h"
48 : : #include "utils/resowner.h"
49 : : #include "utils/syscache.h"
50 : : #include "utils/varlena.h"
51 : :
52 : :
53 : : /*
54 : : * We don't want to log each fetching of a value from a sequence,
55 : : * so we pre-log a few fetches in advance. In the event of
56 : : * crash we can lose (skip over) as many values as we pre-logged.
57 : : */
58 : : #define SEQ_LOG_VALS 32
59 : :
60 : : /*
61 : : * We store a SeqTable item for every sequence we have touched in the current
62 : : * session. This is needed to hold onto nextval/currval state. (We can't
63 : : * rely on the relcache, since it's only, well, a cache, and may decide to
64 : : * discard entries.)
65 : : */
66 : : typedef struct SeqTableData
67 : : {
68 : : Oid relid; /* pg_class OID of this sequence (hash key) */
69 : : RelFileNumber filenumber; /* last seen relfilenumber of this sequence */
70 : : LocalTransactionId lxid; /* xact in which we last did a seq op */
71 : : bool last_valid; /* do we have a valid "last" value? */
72 : : int64 last; /* value last returned by nextval */
73 : : int64 cached; /* last value already cached for nextval */
74 : : /* if last != cached, we have not used up all the cached values */
75 : : int64 increment; /* copy of sequence's increment field */
76 : : /* note that increment is zero until we first do nextval_internal() */
77 : : } SeqTableData;
78 : :
79 : : typedef SeqTableData *SeqTable;
80 : :
81 : : static HTAB *seqhashtab = NULL; /* hash table for SeqTable items */
82 : :
83 : : /*
84 : : * last_used_seq is updated by nextval() to point to the last used
85 : : * sequence.
86 : : */
87 : : static SeqTableData *last_used_seq = NULL;
88 : :
89 : : static void fill_seq_with_data(Relation rel, HeapTuple tuple);
90 : : static void fill_seq_fork_with_data(Relation rel, HeapTuple tuple, ForkNumber forkNum);
91 : : static Relation lock_and_open_sequence(SeqTable seq);
92 : : static void create_seq_hashtable(void);
93 : : static void init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel);
94 : : static Form_pg_sequence_data read_seq_tuple(Relation rel,
95 : : Buffer *buf, HeapTuple seqdatatuple);
96 : : static void init_params(ParseState *pstate, List *options, bool for_identity,
97 : : bool isInit,
98 : : Form_pg_sequence seqform,
99 : : int64 *last_value,
100 : : bool *reset_state,
101 : : bool *is_called,
102 : : bool *need_seq_rewrite,
103 : : List **owned_by);
104 : : static void process_owned_by(Relation seqrel, List *owned_by, bool for_identity);
105 : :
106 : :
107 : : /*
108 : : * DefineSequence
109 : : * Creates a new sequence relation
110 : : */
111 : : ObjectAddress
112 : 1287 : DefineSequence(ParseState *pstate, CreateSeqStmt *seq)
113 : : {
114 : : FormData_pg_sequence seqform;
115 : : int64 last_value;
116 : : bool reset_state;
117 : : bool is_called;
118 : : bool need_seq_rewrite;
119 : : List *owned_by;
120 : 1287 : CreateStmt *stmt = makeNode(CreateStmt);
121 : : Oid seqoid;
122 : : ObjectAddress address;
123 : : Relation rel;
124 : : HeapTuple tuple;
125 : : TupleDesc tupDesc;
126 : : Datum value[SEQ_COL_LASTCOL];
127 : : bool null[SEQ_COL_LASTCOL];
128 : : Datum pgs_values[Natts_pg_sequence];
129 : : bool pgs_nulls[Natts_pg_sequence];
130 : : int i;
131 : :
132 : : /*
133 : : * If if_not_exists was given and a relation with the same name already
134 : : * exists, bail out. (Note: we needn't check this when not if_not_exists,
135 : : * because DefineRelation will complain anyway.)
136 : : */
137 [ + + ]: 1287 : if (seq->if_not_exists)
138 : : {
139 : 10 : RangeVarGetAndCheckCreationNamespace(seq->sequence, NoLock, &seqoid);
140 [ + + ]: 10 : if (OidIsValid(seqoid))
141 : : {
142 : : /*
143 : : * If we are in an extension script, insist that the pre-existing
144 : : * object be a member of the extension, to avoid security risks.
145 : : */
146 : 6 : ObjectAddressSet(address, RelationRelationId, seqoid);
147 : 6 : checkMembershipInCurrentExtension(&address);
148 : :
149 : : /* OK to skip */
150 [ + + ]: 5 : ereport(NOTICE,
151 : : (errcode(ERRCODE_DUPLICATE_TABLE),
152 : : errmsg("relation \"%s\" already exists, skipping",
153 : : seq->sequence->relname)));
154 : 5 : return InvalidObjectAddress;
155 : : }
156 : : }
157 : :
158 : : /* Check and set all option values */
159 : 1281 : init_params(pstate, seq->options, seq->for_identity, true,
160 : : &seqform, &last_value, &reset_state, &is_called,
161 : : &need_seq_rewrite, &owned_by);
162 : :
163 : : /*
164 : : * Create relation (and fill value[] and null[] for the tuple)
165 : : */
166 : 1233 : stmt->tableElts = NIL;
167 [ + + ]: 4932 : for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
168 : : {
169 : 3699 : ColumnDef *coldef = NULL;
170 : :
171 [ + + + - ]: 3699 : switch (i)
172 : : {
173 : 1233 : case SEQ_COL_LASTVAL:
174 : 1233 : coldef = makeColumnDef("last_value", INT8OID, -1, InvalidOid);
175 : 1233 : value[i - 1] = Int64GetDatumFast(last_value);
176 : 1233 : break;
177 : 1233 : case SEQ_COL_LOG:
178 : 1233 : coldef = makeColumnDef("log_cnt", INT8OID, -1, InvalidOid);
179 : 1233 : value[i - 1] = Int64GetDatum((int64) 0);
180 : 1233 : break;
181 : 1233 : case SEQ_COL_CALLED:
182 : 1233 : coldef = makeColumnDef("is_called", BOOLOID, -1, InvalidOid);
183 : 1233 : value[i - 1] = BoolGetDatum(false);
184 : 1233 : break;
185 : : }
186 : :
187 : 3699 : coldef->is_not_null = true;
188 : 3699 : null[i - 1] = false;
189 : :
190 : 3699 : stmt->tableElts = lappend(stmt->tableElts, coldef);
191 : : }
192 : :
193 : 1233 : stmt->relation = seq->sequence;
194 : 1233 : stmt->inhRelations = NIL;
195 : 1233 : stmt->constraints = NIL;
196 : 1233 : stmt->options = NIL;
197 : 1233 : stmt->oncommit = ONCOMMIT_NOOP;
198 : 1233 : stmt->tablespacename = NULL;
199 : 1233 : stmt->if_not_exists = seq->if_not_exists;
200 : :
201 : 1233 : address = DefineRelation(stmt, RELKIND_SEQUENCE, seq->ownerId, NULL, NULL);
202 : 1233 : seqoid = address.objectId;
203 : : Assert(seqoid != InvalidOid);
204 : :
205 : 1233 : rel = sequence_open(seqoid, AccessExclusiveLock);
206 : 1233 : tupDesc = RelationGetDescr(rel);
207 : :
208 : : /* now initialize the sequence's data */
209 : 1233 : tuple = heap_form_tuple(tupDesc, value, null);
210 : 1233 : fill_seq_with_data(rel, tuple);
211 : :
212 : : /* process OWNED BY if given */
213 [ + + ]: 1233 : if (owned_by)
214 : 17 : process_owned_by(rel, owned_by, seq->for_identity);
215 : :
216 : 1217 : sequence_close(rel, NoLock);
217 : :
218 : : /* fill in pg_sequence */
219 : 1217 : rel = table_open(SequenceRelationId, RowExclusiveLock);
220 : 1217 : tupDesc = RelationGetDescr(rel);
221 : :
222 : 1217 : memset(pgs_nulls, 0, sizeof(pgs_nulls));
223 : :
224 : 1217 : pgs_values[Anum_pg_sequence_seqrelid - 1] = ObjectIdGetDatum(seqoid);
225 : 1217 : pgs_values[Anum_pg_sequence_seqtypid - 1] = ObjectIdGetDatum(seqform.seqtypid);
226 : 1217 : pgs_values[Anum_pg_sequence_seqstart - 1] = Int64GetDatumFast(seqform.seqstart);
227 : 1217 : pgs_values[Anum_pg_sequence_seqincrement - 1] = Int64GetDatumFast(seqform.seqincrement);
228 : 1217 : pgs_values[Anum_pg_sequence_seqmax - 1] = Int64GetDatumFast(seqform.seqmax);
229 : 1217 : pgs_values[Anum_pg_sequence_seqmin - 1] = Int64GetDatumFast(seqform.seqmin);
230 : 1217 : pgs_values[Anum_pg_sequence_seqcache - 1] = Int64GetDatumFast(seqform.seqcache);
231 : 1217 : pgs_values[Anum_pg_sequence_seqcycle - 1] = BoolGetDatum(seqform.seqcycle);
232 : :
233 : 1217 : tuple = heap_form_tuple(tupDesc, pgs_values, pgs_nulls);
234 : 1217 : CatalogTupleInsert(rel, tuple);
235 : :
236 : 1217 : heap_freetuple(tuple);
237 : 1217 : table_close(rel, RowExclusiveLock);
238 : :
239 : 1217 : return address;
240 : : }
241 : :
242 : : /*
243 : : * Reset a sequence to its initial value.
244 : : *
245 : : * The change is made transactionally, so that on failure of the current
246 : : * transaction, the sequence will be restored to its previous state.
247 : : * We do that by creating a whole new relfilenumber for the sequence; so this
248 : : * works much like the rewriting forms of ALTER TABLE.
249 : : *
250 : : * Caller is assumed to have acquired AccessExclusiveLock on the sequence,
251 : : * which must not be released until end of transaction. Caller is also
252 : : * responsible for permissions checking.
253 : : */
254 : : void
255 : 23 : ResetSequence(Oid seq_relid)
256 : : {
257 : : Relation seq_rel;
258 : : SeqTable elm;
259 : : Form_pg_sequence_data seq;
260 : : Buffer buf;
261 : : HeapTupleData seqdatatuple;
262 : : HeapTuple tuple;
263 : : HeapTuple pgstuple;
264 : : Form_pg_sequence pgsform;
265 : : int64 startv;
266 : :
267 : : /*
268 : : * Read the old sequence. This does a bit more work than really
269 : : * necessary, but it's simple, and we do want to double-check that it's
270 : : * indeed a sequence.
271 : : */
272 : 23 : init_sequence(seq_relid, &elm, &seq_rel);
273 : 23 : (void) read_seq_tuple(seq_rel, &buf, &seqdatatuple);
274 : :
275 : 23 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(seq_relid));
276 [ - + ]: 23 : if (!HeapTupleIsValid(pgstuple))
277 [ # # ]: 0 : elog(ERROR, "cache lookup failed for sequence %u", seq_relid);
278 : 23 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
279 : 23 : startv = pgsform->seqstart;
280 : 23 : ReleaseSysCache(pgstuple);
281 : :
282 : : /*
283 : : * Copy the existing sequence tuple.
284 : : */
285 : 23 : tuple = heap_copytuple(&seqdatatuple);
286 : :
287 : : /* Now we're done with the old page */
288 : 23 : UnlockReleaseBuffer(buf);
289 : :
290 : : /*
291 : : * Modify the copied tuple to execute the restart (compare the RESTART
292 : : * action in AlterSequence)
293 : : */
294 : 23 : seq = (Form_pg_sequence_data) GETSTRUCT(tuple);
295 : 23 : seq->last_value = startv;
296 : 23 : seq->is_called = false;
297 : 23 : seq->log_cnt = 0;
298 : :
299 : : /*
300 : : * Create a new storage file for the sequence.
301 : : */
302 : 23 : RelationSetNewRelfilenumber(seq_rel, seq_rel->rd_rel->relpersistence);
303 : :
304 : : /*
305 : : * Ensure sequence's relfrozenxid is at 0, since it won't contain any
306 : : * unfrozen XIDs. Same with relminmxid, since a sequence will never
307 : : * contain multixacts.
308 : : */
309 : : Assert(seq_rel->rd_rel->relfrozenxid == InvalidTransactionId);
310 : : Assert(seq_rel->rd_rel->relminmxid == InvalidMultiXactId);
311 : :
312 : : /*
313 : : * Insert the modified tuple into the new storage file.
314 : : */
315 : 23 : fill_seq_with_data(seq_rel, tuple);
316 : :
317 : : /* Clear local cache so that we don't think we have cached numbers */
318 : : /* Note that we do not change the currval() state */
319 : 23 : elm->cached = elm->last;
320 : :
321 : 23 : sequence_close(seq_rel, NoLock);
322 : 23 : }
323 : :
324 : : /*
325 : : * Initialize a sequence's relation with the specified tuple as content
326 : : *
327 : : * This handles unlogged sequences by writing to both the main and the init
328 : : * fork as necessary.
329 : : */
330 : : static void
331 : 1427 : fill_seq_with_data(Relation rel, HeapTuple tuple)
332 : : {
333 : 1427 : fill_seq_fork_with_data(rel, tuple, MAIN_FORKNUM);
334 : :
335 [ + + ]: 1427 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
336 : : {
337 : : SMgrRelation srel;
338 : :
339 : 74 : srel = smgropen(rel->rd_locator, INVALID_PROC_NUMBER);
340 : 74 : smgrcreate(srel, INIT_FORKNUM, false);
341 : 74 : log_smgrcreate(&rel->rd_locator, INIT_FORKNUM);
342 : 74 : fill_seq_fork_with_data(rel, tuple, INIT_FORKNUM);
343 : 74 : FlushRelationBuffers(rel);
344 : 74 : smgrclose(srel);
345 : : }
346 : 1427 : }
347 : :
348 : : /*
349 : : * Initialize a sequence's relation fork with the specified tuple as content
350 : : */
351 : : static void
352 : 1501 : fill_seq_fork_with_data(Relation rel, HeapTuple tuple, ForkNumber forkNum)
353 : : {
354 : : Buffer buf;
355 : : Page page;
356 : : sequence_magic *sm;
357 : : OffsetNumber offnum;
358 : :
359 : : /* Initialize first page of relation with special magic number */
360 : :
361 : 1501 : buf = ExtendBufferedRel(BMR_REL(rel), forkNum, NULL,
362 : : EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
363 : : Assert(BufferGetBlockNumber(buf) == 0);
364 : :
365 : 1501 : page = BufferGetPage(buf);
366 : :
367 : 1501 : PageInit(page, BufferGetPageSize(buf), sizeof(sequence_magic));
368 : 1501 : sm = (sequence_magic *) PageGetSpecialPointer(page);
369 : 1501 : sm->magic = SEQ_MAGIC;
370 : :
371 : : /* Now insert sequence tuple */
372 : :
373 : : /*
374 : : * For heap_insert() that'd be done by heap_prepare_insert(), we don't use
375 : : * that here, so have to do it manually (this is necessary, as the
376 : : * heap_form_tuple() in callers will have marked the tuple as a datum
377 : : * tuple, which needs to be unset before inserting).
378 : : */
379 : 1501 : tuple->t_data->t_infomask &= ~(HEAP_XACT_MASK);
380 : 1501 : tuple->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
381 : 1501 : tuple->t_data->t_infomask |= HEAP_XMAX_INVALID;
382 : :
383 : : /*
384 : : * Since VACUUM does not process sequences, we have to force the tuple to
385 : : * have xmin = FrozenTransactionId now. Otherwise it would become
386 : : * invisible to SELECTs after 2G transactions. It is okay to do this
387 : : * because if the current transaction aborts, no other xact will ever
388 : : * examine the sequence tuple anyway.
389 : : *
390 : : * Don't need to unset HEAP_IS_DATUM, it's part of HEAP_XACT_MASK, cleared
391 : : * above.
392 : : */
393 : 1501 : HeapTupleHeaderSetXmin(tuple->t_data, FrozenTransactionId);
394 : 1501 : HeapTupleHeaderSetXminFrozen(tuple->t_data);
395 : 1501 : HeapTupleHeaderSetCmin(tuple->t_data, FirstCommandId);
396 : 1501 : HeapTupleHeaderSetXmax(tuple->t_data, InvalidTransactionId);
397 : 1501 : ItemPointerSet(&tuple->t_data->t_ctid, 0, FirstOffsetNumber);
398 : :
399 : : /* check the comment above nextval_internal()'s equivalent call. */
400 [ + + + + : 1501 : if (RelationNeedsWAL(rel))
+ + - + ]
401 : 1098 : GetTopTransactionId();
402 : :
403 : 1501 : START_CRIT_SECTION();
404 : :
405 : 1501 : MarkBufferDirty(buf);
406 : :
407 : 1501 : offnum = PageAddItem(page, tuple->t_data, tuple->t_len, InvalidOffsetNumber, false, false);
408 [ - + ]: 1501 : if (offnum != FirstOffsetNumber)
409 [ # # ]: 0 : elog(ERROR, "failed to add sequence tuple to page");
410 : :
411 : : /* XLOG stuff */
412 [ + + + + : 1501 : if (RelationNeedsWAL(rel) || forkNum == INIT_FORKNUM)
+ + + - +
+ ]
413 : : {
414 : : xl_seq_rec xlrec;
415 : : XLogRecPtr recptr;
416 : :
417 : 1172 : XLogBeginInsert();
418 : 1172 : XLogRegisterBuffer(0, buf, REGBUF_WILL_INIT);
419 : :
420 : 1172 : xlrec.locator = rel->rd_locator;
421 : :
422 : 1172 : XLogRegisterData(&xlrec, sizeof(xl_seq_rec));
423 : 1172 : XLogRegisterData(tuple->t_data, tuple->t_len);
424 : :
425 : 1172 : recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG);
426 : :
427 : 1172 : PageSetLSN(page, recptr);
428 : : }
429 : :
430 : 1501 : END_CRIT_SECTION();
431 : :
432 : 1501 : UnlockReleaseBuffer(buf);
433 : 1501 : }
434 : :
435 : : /*
436 : : * AlterSequence
437 : : *
438 : : * Modify the definition of a sequence relation
439 : : */
440 : : ObjectAddress
441 : 1005 : AlterSequence(ParseState *pstate, AlterSeqStmt *stmt)
442 : : {
443 : : Oid relid;
444 : : SeqTable elm;
445 : : Relation seqrel;
446 : : Buffer buf;
447 : : HeapTupleData datatuple;
448 : : Form_pg_sequence seqform;
449 : : Form_pg_sequence_data newdataform;
450 : : bool need_seq_rewrite;
451 : : List *owned_by;
452 : : ObjectAddress address;
453 : : Relation rel;
454 : : HeapTuple seqtuple;
455 : 1005 : bool reset_state = false;
456 : : bool is_called;
457 : : int64 last_value;
458 : : HeapTuple newdatatuple;
459 : :
460 : : /* Open and lock sequence, and check for ownership along the way. */
461 : 1005 : relid = RangeVarGetRelidExtended(stmt->sequence,
462 : : ShareRowExclusiveLock,
463 : 1005 : stmt->missing_ok ? RVR_MISSING_OK : 0,
464 : : RangeVarCallbackOwnsRelation,
465 : : NULL);
466 [ + + ]: 1001 : if (relid == InvalidOid)
467 : : {
468 [ + - ]: 4 : ereport(NOTICE,
469 : : (errmsg("relation \"%s\" does not exist, skipping",
470 : : stmt->sequence->relname)));
471 : 4 : return InvalidObjectAddress;
472 : : }
473 : :
474 : 997 : init_sequence(relid, &elm, &seqrel);
475 : :
476 : 993 : rel = table_open(SequenceRelationId, RowExclusiveLock);
477 : 993 : seqtuple = SearchSysCacheCopy1(SEQRELID,
478 : : ObjectIdGetDatum(relid));
479 [ - + ]: 993 : if (!HeapTupleIsValid(seqtuple))
480 [ # # ]: 0 : elog(ERROR, "cache lookup failed for sequence %u",
481 : : relid);
482 : :
483 : 993 : seqform = (Form_pg_sequence) GETSTRUCT(seqtuple);
484 : :
485 : : /* lock page buffer and read tuple into new sequence structure */
486 : 993 : (void) read_seq_tuple(seqrel, &buf, &datatuple);
487 : :
488 : : /* copy the existing sequence data tuple, so it can be modified locally */
489 : 993 : newdatatuple = heap_copytuple(&datatuple);
490 : 993 : newdataform = (Form_pg_sequence_data) GETSTRUCT(newdatatuple);
491 : 993 : last_value = newdataform->last_value;
492 : 993 : is_called = newdataform->is_called;
493 : :
494 : 993 : UnlockReleaseBuffer(buf);
495 : :
496 : : /* Check and set new values */
497 : 993 : init_params(pstate, stmt->options, stmt->for_identity, false,
498 : : seqform, &last_value, &reset_state, &is_called,
499 : : &need_seq_rewrite, &owned_by);
500 : :
501 : : /* If needed, rewrite the sequence relation itself */
502 [ + + ]: 973 : if (need_seq_rewrite)
503 : : {
504 : : /* check the comment above nextval_internal()'s equivalent call. */
505 [ + + + + : 123 : if (RelationNeedsWAL(seqrel))
+ - + - ]
506 : 114 : GetTopTransactionId();
507 : :
508 : : /*
509 : : * Create a new storage file for the sequence, making the state
510 : : * changes transactional.
511 : : */
512 : 123 : RelationSetNewRelfilenumber(seqrel, seqrel->rd_rel->relpersistence);
513 : :
514 : : /*
515 : : * Ensure sequence's relfrozenxid is at 0, since it won't contain any
516 : : * unfrozen XIDs. Same with relminmxid, since a sequence will never
517 : : * contain multixacts.
518 : : */
519 : : Assert(seqrel->rd_rel->relfrozenxid == InvalidTransactionId);
520 : : Assert(seqrel->rd_rel->relminmxid == InvalidMultiXactId);
521 : :
522 : : /*
523 : : * Insert the modified tuple into the new storage file.
524 : : */
525 : 123 : newdataform->last_value = last_value;
526 : 123 : newdataform->is_called = is_called;
527 [ + + ]: 123 : if (reset_state)
528 : 122 : newdataform->log_cnt = 0;
529 : 123 : fill_seq_with_data(seqrel, newdatatuple);
530 : : }
531 : :
532 : : /* Clear local cache so that we don't think we have cached numbers */
533 : : /* Note that we do not change the currval() state */
534 : 973 : elm->cached = elm->last;
535 : :
536 : : /* process OWNED BY if given */
537 [ + + ]: 973 : if (owned_by)
538 : 841 : process_owned_by(seqrel, owned_by, stmt->for_identity);
539 : :
540 : : /* update the pg_sequence tuple (we could skip this in some cases...) */
541 : 969 : CatalogTupleUpdate(rel, &seqtuple->t_self, seqtuple);
542 : :
543 [ - + ]: 969 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
544 : :
545 : 969 : ObjectAddressSet(address, RelationRelationId, relid);
546 : :
547 : 969 : table_close(rel, RowExclusiveLock);
548 : 969 : sequence_close(seqrel, NoLock);
549 : :
550 : 969 : return address;
551 : : }
552 : :
553 : : void
554 : 48 : SequenceChangePersistence(Oid relid, char newrelpersistence)
555 : : {
556 : : SeqTable elm;
557 : : Relation seqrel;
558 : : Buffer buf;
559 : : HeapTupleData seqdatatuple;
560 : :
561 : : /*
562 : : * ALTER SEQUENCE acquires this lock earlier. If we're processing an
563 : : * owned sequence for ALTER TABLE, lock now. Without the lock, we'd
564 : : * discard increments from nextval() calls (in other sessions) between
565 : : * this function's buffer unlock and this transaction's commit.
566 : : */
567 : 48 : LockRelationOid(relid, AccessExclusiveLock);
568 : 48 : init_sequence(relid, &elm, &seqrel);
569 : :
570 : : /* check the comment above nextval_internal()'s equivalent call. */
571 [ + + - + : 48 : if (RelationNeedsWAL(seqrel))
- - - - ]
572 : 28 : GetTopTransactionId();
573 : :
574 : 48 : (void) read_seq_tuple(seqrel, &buf, &seqdatatuple);
575 : 48 : RelationSetNewRelfilenumber(seqrel, newrelpersistence);
576 : 48 : fill_seq_with_data(seqrel, &seqdatatuple);
577 : 48 : UnlockReleaseBuffer(buf);
578 : :
579 : 48 : sequence_close(seqrel, NoLock);
580 : 48 : }
581 : :
582 : : void
583 : 690 : DeleteSequenceTuple(Oid relid)
584 : : {
585 : : Relation rel;
586 : : HeapTuple tuple;
587 : :
588 : 690 : rel = table_open(SequenceRelationId, RowExclusiveLock);
589 : :
590 : 690 : tuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
591 [ - + ]: 690 : if (!HeapTupleIsValid(tuple))
592 [ # # ]: 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
593 : :
594 : 690 : CatalogTupleDelete(rel, &tuple->t_self);
595 : :
596 : 690 : ReleaseSysCache(tuple);
597 : 690 : table_close(rel, RowExclusiveLock);
598 : 690 : }
599 : :
600 : : /*
601 : : * Note: nextval with a text argument is no longer exported as a pg_proc
602 : : * entry, but we keep it around to ease porting of C code that may have
603 : : * called the function directly.
604 : : */
605 : : Datum
606 : 9 : nextval(PG_FUNCTION_ARGS)
607 : : {
608 : 9 : text *seqin = PG_GETARG_TEXT_PP(0);
609 : : RangeVar *sequence;
610 : : Oid relid;
611 : :
612 : 9 : sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin));
613 : :
614 : : /*
615 : : * XXX: This is not safe in the presence of concurrent DDL, but acquiring
616 : : * a lock here is more expensive than letting nextval_internal do it,
617 : : * since the latter maintains a cache that keeps us from hitting the lock
618 : : * manager more than once per transaction. It's not clear whether the
619 : : * performance penalty is material in practice, but for now, we do it this
620 : : * way.
621 : : */
622 : 9 : relid = RangeVarGetRelid(sequence, NoLock, false);
623 : :
624 : 9 : PG_RETURN_INT64(nextval_internal(relid, true));
625 : : }
626 : :
627 : : Datum
628 : 264751 : nextval_oid(PG_FUNCTION_ARGS)
629 : : {
630 : 264751 : Oid relid = PG_GETARG_OID(0);
631 : :
632 : 264751 : PG_RETURN_INT64(nextval_internal(relid, true));
633 : : }
634 : :
635 : : int64
636 : 286880 : nextval_internal(Oid relid, bool check_permissions)
637 : : {
638 : : SeqTable elm;
639 : : Relation seqrel;
640 : : Buffer buf;
641 : : Page page;
642 : : HeapTuple pgstuple;
643 : : Form_pg_sequence pgsform;
644 : : HeapTupleData seqdatatuple;
645 : : Form_pg_sequence_data seq;
646 : : int64 incby,
647 : : maxv,
648 : : minv,
649 : : cache,
650 : : log,
651 : : fetch,
652 : : last;
653 : : int64 result,
654 : : next,
655 : 286880 : rescnt = 0;
656 : : bool cycle;
657 : 286880 : bool logit = false;
658 : :
659 : : /* open and lock sequence */
660 : 286880 : init_sequence(relid, &elm, &seqrel);
661 : :
662 [ + + + + ]: 551640 : if (check_permissions &&
663 : 264760 : pg_class_aclcheck(elm->relid, GetUserId(),
664 : : ACL_USAGE | ACL_UPDATE) != ACLCHECK_OK)
665 [ + - ]: 4 : ereport(ERROR,
666 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
667 : : errmsg("permission denied for sequence %s",
668 : : RelationGetRelationName(seqrel))));
669 : :
670 : : /* read-only transactions may only modify temp sequences */
671 [ + + ]: 286876 : if (!seqrel->rd_islocaltemp)
672 : 205583 : PreventCommandIfReadOnly("nextval()");
673 : :
674 : : /*
675 : : * Forbid this during parallel operation because, to make it work, the
676 : : * cooperating backends would need to share the backend-local cached
677 : : * sequence information. Currently, we don't support that.
678 : : */
679 : 286872 : PreventCommandIfParallelMode("nextval()");
680 : :
681 [ + + ]: 286872 : if (elm->last != elm->cached) /* some numbers were cached */
682 : : {
683 : : Assert(elm->last_valid);
684 : : Assert(elm->increment != 0);
685 : 8 : elm->last += elm->increment;
686 : 8 : sequence_close(seqrel, NoLock);
687 : 8 : last_used_seq = elm;
688 : 8 : return elm->last;
689 : : }
690 : :
691 : 286864 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
692 [ - + ]: 286864 : if (!HeapTupleIsValid(pgstuple))
693 [ # # ]: 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
694 : 286864 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
695 : 286864 : incby = pgsform->seqincrement;
696 : 286864 : maxv = pgsform->seqmax;
697 : 286864 : minv = pgsform->seqmin;
698 : 286864 : cache = pgsform->seqcache;
699 : 286864 : cycle = pgsform->seqcycle;
700 : 286864 : ReleaseSysCache(pgstuple);
701 : :
702 : : /* lock page buffer and read tuple */
703 : 286864 : seq = read_seq_tuple(seqrel, &buf, &seqdatatuple);
704 : 286864 : page = BufferGetPage(buf);
705 : :
706 : 286864 : last = next = result = seq->last_value;
707 : 286864 : fetch = cache;
708 : 286864 : log = seq->log_cnt;
709 : :
710 [ + + ]: 286864 : if (!seq->is_called)
711 : : {
712 : 791 : rescnt++; /* return last_value if not is_called */
713 : 791 : fetch--;
714 : : }
715 : :
716 : : /*
717 : : * Decide whether we should emit a WAL log record. If so, force up the
718 : : * fetch count to grab SEQ_LOG_VALS more values than we actually need to
719 : : * cache. (These will then be usable without logging.)
720 : : *
721 : : * If this is the first nextval after a checkpoint, we must force a new
722 : : * WAL record to be written anyway, else replay starting from the
723 : : * checkpoint would fail to advance the sequence past the logged values.
724 : : * In this case we may as well fetch extra values.
725 : : */
726 [ + + + + ]: 286864 : if (log < fetch || !seq->is_called)
727 : : {
728 : : /* forced log to satisfy local demand for values */
729 : 5873 : fetch = log = fetch + SEQ_LOG_VALS;
730 : 5873 : logit = true;
731 : : }
732 : : else
733 : : {
734 : 280991 : XLogRecPtr redoptr = GetRedoRecPtr();
735 : :
736 [ + + ]: 280991 : if (PageGetLSN(page) <= redoptr)
737 : : {
738 : : /* last update of seq was before checkpoint */
739 : 118017 : fetch = log = fetch + SEQ_LOG_VALS;
740 : 118017 : logit = true;
741 : : }
742 : : }
743 : :
744 [ + + ]: 4536387 : while (fetch) /* try to fetch cache [+ log ] numbers */
745 : : {
746 : : /*
747 : : * Check MAXVALUE for ascending sequences and MINVALUE for descending
748 : : * sequences
749 : : */
750 [ + + ]: 4249560 : if (incby > 0)
751 : : {
752 : : /* ascending sequence */
753 [ + - + + : 4249207 : if ((maxv >= 0 && next > maxv - incby) ||
- + ]
754 [ # # ]: 0 : (maxv < 0 && next + incby > maxv))
755 : : {
756 [ + + ]: 25 : if (rescnt > 0)
757 : 15 : break; /* stop fetching */
758 [ + + ]: 10 : if (!cycle)
759 [ + - ]: 6 : ereport(ERROR,
760 : : (errcode(ERRCODE_SEQUENCE_GENERATOR_LIMIT_EXCEEDED),
761 : : errmsg("nextval: reached maximum value of sequence \"%s\" (%" PRId64 ")",
762 : : RelationGetRelationName(seqrel),
763 : : maxv)));
764 : 4 : next = minv;
765 : : }
766 : : else
767 : 4249182 : next += incby;
768 : : }
769 : : else
770 : : {
771 : : /* descending sequence */
772 [ + - + + : 353 : if ((minv < 0 && next < minv - incby) ||
- + ]
773 [ # # ]: 0 : (minv >= 0 && next + incby < minv))
774 : : {
775 [ + + ]: 20 : if (rescnt > 0)
776 : 12 : break; /* stop fetching */
777 [ + + ]: 8 : if (!cycle)
778 [ + - ]: 4 : ereport(ERROR,
779 : : (errcode(ERRCODE_SEQUENCE_GENERATOR_LIMIT_EXCEEDED),
780 : : errmsg("nextval: reached minimum value of sequence \"%s\" (%" PRId64 ")",
781 : : RelationGetRelationName(seqrel),
782 : : minv)));
783 : 4 : next = maxv;
784 : : }
785 : : else
786 : 333 : next += incby;
787 : : }
788 : 4249523 : fetch--;
789 [ + + ]: 4249523 : if (rescnt < cache)
790 : : {
791 : 286099 : log--;
792 : 286099 : rescnt++;
793 : 286099 : last = next;
794 [ + + ]: 286099 : if (rescnt == 1) /* if it's first result - */
795 : 286063 : result = next; /* it's what to return */
796 : : }
797 : : }
798 : :
799 : 286854 : log -= fetch; /* adjust for any unfetched numbers */
800 : : Assert(log >= 0);
801 : :
802 : : /* save info in local cache */
803 : 286854 : elm->increment = incby;
804 : 286854 : elm->last = result; /* last returned number */
805 : 286854 : elm->cached = last; /* last fetched number */
806 : 286854 : elm->last_valid = true;
807 : :
808 : 286854 : last_used_seq = elm;
809 : :
810 : : /*
811 : : * If something needs to be WAL logged, acquire an xid, so this
812 : : * transaction's commit will trigger a WAL flush and wait for syncrep.
813 : : * It's sufficient to ensure the toplevel transaction has an xid, no need
814 : : * to assign xids subxacts, that'll already trigger an appropriate wait.
815 : : * (Have to do that here, so we're outside the critical section)
816 : : */
817 [ + + + + : 286854 : if (logit && RelationNeedsWAL(seqrel))
+ + + + +
- ]
818 : 5704 : GetTopTransactionId();
819 : :
820 : : /* ready to change the on-disk (or really, in-buffer) tuple */
821 : 286854 : START_CRIT_SECTION();
822 : :
823 : : /*
824 : : * We must mark the buffer dirty before doing XLogInsert(); see notes in
825 : : * SyncOneBuffer(). However, we don't apply the desired changes just yet.
826 : : * This looks like a violation of the buffer update protocol, but it is in
827 : : * fact safe because we hold exclusive lock on the buffer. Any other
828 : : * process, including a checkpoint, that tries to examine the buffer
829 : : * contents will block until we release the lock, and then will see the
830 : : * final state that we install below.
831 : : */
832 : 286854 : MarkBufferDirty(buf);
833 : :
834 : : /* XLOG stuff */
835 [ + + + + : 286854 : if (logit && RelationNeedsWAL(seqrel))
+ + + + +
- ]
836 : : {
837 : : xl_seq_rec xlrec;
838 : : XLogRecPtr recptr;
839 : :
840 : : /*
841 : : * We don't log the current state of the tuple, but rather the state
842 : : * as it would appear after "log" more fetches. This lets us skip
843 : : * that many future WAL records, at the cost that we lose those
844 : : * sequence values if we crash.
845 : : */
846 : 5704 : XLogBeginInsert();
847 : 5704 : XLogRegisterBuffer(0, buf, REGBUF_WILL_INIT);
848 : :
849 : : /* set values that will be saved in xlog */
850 : 5704 : seq->last_value = next;
851 : 5704 : seq->is_called = true;
852 : 5704 : seq->log_cnt = 0;
853 : :
854 : 5704 : xlrec.locator = seqrel->rd_locator;
855 : :
856 : 5704 : XLogRegisterData(&xlrec, sizeof(xl_seq_rec));
857 : 5704 : XLogRegisterData(seqdatatuple.t_data, seqdatatuple.t_len);
858 : :
859 : 5704 : recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG);
860 : :
861 : 5704 : PageSetLSN(page, recptr);
862 : : }
863 : :
864 : : /* Now update sequence tuple to the intended final state */
865 : 286854 : seq->last_value = last; /* last fetched number */
866 : 286854 : seq->is_called = true;
867 : 286854 : seq->log_cnt = log; /* how much is logged */
868 : :
869 : 286854 : END_CRIT_SECTION();
870 : :
871 : 286854 : UnlockReleaseBuffer(buf);
872 : :
873 : 286854 : sequence_close(seqrel, NoLock);
874 : :
875 : 286854 : return result;
876 : : }
877 : :
878 : : Datum
879 : 77 : currval_oid(PG_FUNCTION_ARGS)
880 : : {
881 : 77 : Oid relid = PG_GETARG_OID(0);
882 : : int64 result;
883 : : SeqTable elm;
884 : : Relation seqrel;
885 : :
886 : : /* open and lock sequence */
887 : 77 : init_sequence(relid, &elm, &seqrel);
888 : :
889 [ + + ]: 77 : if (pg_class_aclcheck(elm->relid, GetUserId(),
890 : : ACL_SELECT | ACL_USAGE) != ACLCHECK_OK)
891 [ + - ]: 4 : ereport(ERROR,
892 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
893 : : errmsg("permission denied for sequence %s",
894 : : RelationGetRelationName(seqrel))));
895 : :
896 [ + + ]: 73 : if (!elm->last_valid)
897 [ + - ]: 4 : ereport(ERROR,
898 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
899 : : errmsg("currval of sequence \"%s\" is not yet defined in this session",
900 : : RelationGetRelationName(seqrel))));
901 : :
902 : 69 : result = elm->last;
903 : :
904 : 69 : sequence_close(seqrel, NoLock);
905 : :
906 : 69 : PG_RETURN_INT64(result);
907 : : }
908 : :
909 : : Datum
910 : 32 : lastval(PG_FUNCTION_ARGS)
911 : : {
912 : : Relation seqrel;
913 : : int64 result;
914 : :
915 [ + + ]: 32 : if (last_used_seq == NULL)
916 [ + - ]: 4 : ereport(ERROR,
917 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
918 : : errmsg("lastval is not yet defined in this session")));
919 : :
920 : : /* Someone may have dropped the sequence since the last nextval() */
921 [ + + ]: 28 : if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(last_used_seq->relid)))
922 [ + - ]: 4 : ereport(ERROR,
923 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
924 : : errmsg("lastval is not yet defined in this session")));
925 : :
926 : 24 : seqrel = lock_and_open_sequence(last_used_seq);
927 : :
928 : : /* nextval() must have already been called for this sequence */
929 : : Assert(last_used_seq->last_valid);
930 : :
931 [ + + ]: 24 : if (pg_class_aclcheck(last_used_seq->relid, GetUserId(),
932 : : ACL_SELECT | ACL_USAGE) != ACLCHECK_OK)
933 [ + - ]: 4 : ereport(ERROR,
934 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
935 : : errmsg("permission denied for sequence %s",
936 : : RelationGetRelationName(seqrel))));
937 : :
938 : 20 : result = last_used_seq->last;
939 : 20 : sequence_close(seqrel, NoLock);
940 : :
941 : 20 : PG_RETURN_INT64(result);
942 : : }
943 : :
944 : : /*
945 : : * Main internal procedure that handles 2 & 3 arg forms of SETVAL.
946 : : *
947 : : * Note that the 3 arg version (which sets the is_called flag) is
948 : : * only for use in pg_dump, and setting the is_called flag may not
949 : : * work if multiple users are attached to the database and referencing
950 : : * the sequence (unlikely if pg_dump is restoring it).
951 : : *
952 : : * It is necessary to have the 3 arg version so that pg_dump can
953 : : * restore the state of a sequence exactly during data-only restores -
954 : : * it is the only way to clear the is_called flag in an existing
955 : : * sequence.
956 : : */
957 : : void
958 : 371 : SetSequence(Oid relid, int64 next, bool iscalled)
959 : : {
960 : : SeqTable elm;
961 : : Relation seqrel;
962 : : Buffer buf;
963 : : HeapTupleData seqdatatuple;
964 : : Form_pg_sequence_data seq;
965 : : HeapTuple pgstuple;
966 : : Form_pg_sequence pgsform;
967 : : int64 maxv,
968 : : minv;
969 : :
970 : : /* open and lock sequence */
971 : 371 : init_sequence(relid, &elm, &seqrel);
972 : :
973 [ + + ]: 371 : if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
974 [ + - ]: 4 : ereport(ERROR,
975 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
976 : : errmsg("permission denied for sequence %s",
977 : : RelationGetRelationName(seqrel))));
978 : :
979 : 367 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
980 [ - + ]: 367 : if (!HeapTupleIsValid(pgstuple))
981 [ # # ]: 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
982 : 367 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
983 : 367 : maxv = pgsform->seqmax;
984 : 367 : minv = pgsform->seqmin;
985 : 367 : ReleaseSysCache(pgstuple);
986 : :
987 : : /* read-only transactions may only modify temp sequences */
988 [ + + ]: 367 : if (!seqrel->rd_islocaltemp)
989 : 195 : PreventCommandIfReadOnly("setval()");
990 : :
991 : : /*
992 : : * Forbid this during parallel operation because, to make it work, the
993 : : * cooperating backends would need to share the backend-local cached
994 : : * sequence information. Currently, we don't support that.
995 : : */
996 : 363 : PreventCommandIfParallelMode("setval()");
997 : :
998 : : /* lock page buffer and read tuple */
999 : 363 : seq = read_seq_tuple(seqrel, &buf, &seqdatatuple);
1000 : :
1001 [ + + + + ]: 363 : if ((next < minv) || (next > maxv))
1002 [ + - ]: 8 : ereport(ERROR,
1003 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1004 : : errmsg("setval: value %" PRId64 " is out of bounds for sequence \"%s\" (%" PRId64 "..%" PRId64 ")",
1005 : : next, RelationGetRelationName(seqrel),
1006 : : minv, maxv)));
1007 : :
1008 : : /* Set the currval() state only if iscalled = true */
1009 [ + + ]: 355 : if (iscalled)
1010 : : {
1011 : 137 : elm->last = next; /* last returned number */
1012 : 137 : elm->last_valid = true;
1013 : : }
1014 : :
1015 : : /* In any case, forget any future cached numbers */
1016 : 355 : elm->cached = elm->last;
1017 : :
1018 : : /* check the comment above nextval_internal()'s equivalent call. */
1019 [ + + + + : 355 : if (RelationNeedsWAL(seqrel))
+ + + - ]
1020 : 167 : GetTopTransactionId();
1021 : :
1022 : : /* ready to change the on-disk (or really, in-buffer) tuple */
1023 : 355 : START_CRIT_SECTION();
1024 : :
1025 : 355 : seq->last_value = next; /* last fetched number */
1026 : 355 : seq->is_called = iscalled;
1027 : 355 : seq->log_cnt = 0;
1028 : :
1029 : 355 : MarkBufferDirty(buf);
1030 : :
1031 : : /* XLOG stuff */
1032 [ + + + + : 355 : if (RelationNeedsWAL(seqrel))
+ + + - ]
1033 : : {
1034 : : xl_seq_rec xlrec;
1035 : : XLogRecPtr recptr;
1036 : 167 : Page page = BufferGetPage(buf);
1037 : :
1038 : 167 : XLogBeginInsert();
1039 : 167 : XLogRegisterBuffer(0, buf, REGBUF_WILL_INIT);
1040 : :
1041 : 167 : xlrec.locator = seqrel->rd_locator;
1042 : 167 : XLogRegisterData(&xlrec, sizeof(xl_seq_rec));
1043 : 167 : XLogRegisterData(seqdatatuple.t_data, seqdatatuple.t_len);
1044 : :
1045 : 167 : recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG);
1046 : :
1047 : 167 : PageSetLSN(page, recptr);
1048 : : }
1049 : :
1050 : 355 : END_CRIT_SECTION();
1051 : :
1052 : 355 : UnlockReleaseBuffer(buf);
1053 : :
1054 : 355 : sequence_close(seqrel, NoLock);
1055 : 355 : }
1056 : :
1057 : : /*
1058 : : * Implement the 2 arg setval procedure.
1059 : : * See SetSequence for discussion.
1060 : : */
1061 : : Datum
1062 : 95 : setval_oid(PG_FUNCTION_ARGS)
1063 : : {
1064 : 95 : Oid relid = PG_GETARG_OID(0);
1065 : 95 : int64 next = PG_GETARG_INT64(1);
1066 : :
1067 : 95 : SetSequence(relid, next, true);
1068 : :
1069 : 79 : PG_RETURN_INT64(next);
1070 : : }
1071 : :
1072 : : /*
1073 : : * Implement the 3 arg setval procedure.
1074 : : * See SetSequence for discussion.
1075 : : */
1076 : : Datum
1077 : 247 : setval3_oid(PG_FUNCTION_ARGS)
1078 : : {
1079 : 247 : Oid relid = PG_GETARG_OID(0);
1080 : 247 : int64 next = PG_GETARG_INT64(1);
1081 : 247 : bool iscalled = PG_GETARG_BOOL(2);
1082 : :
1083 : 247 : SetSequence(relid, next, iscalled);
1084 : :
1085 : 247 : PG_RETURN_INT64(next);
1086 : : }
1087 : :
1088 : :
1089 : : /*
1090 : : * Open the sequence and acquire lock if needed
1091 : : *
1092 : : * If we haven't touched the sequence already in this transaction,
1093 : : * we need to acquire a lock. We arrange for the lock to
1094 : : * be owned by the top transaction, so that we don't need to do it
1095 : : * more than once per xact.
1096 : : */
1097 : : static Relation
1098 : 288497 : lock_and_open_sequence(SeqTable seq)
1099 : : {
1100 : 288497 : LocalTransactionId thislxid = MyProc->vxid.lxid;
1101 : :
1102 : : /* Get the lock if not already held in this xact */
1103 [ + + ]: 288497 : if (seq->lxid != thislxid)
1104 : : {
1105 : : ResourceOwner currentOwner;
1106 : :
1107 : 3314 : currentOwner = CurrentResourceOwner;
1108 : 3314 : CurrentResourceOwner = TopTransactionResourceOwner;
1109 : :
1110 : 3314 : LockRelationOid(seq->relid, RowExclusiveLock);
1111 : :
1112 : 3314 : CurrentResourceOwner = currentOwner;
1113 : :
1114 : : /* Flag that we have a lock in the current xact */
1115 : 3314 : seq->lxid = thislxid;
1116 : : }
1117 : :
1118 : : /* We now know we have the lock, and can safely open the rel */
1119 : 288497 : return sequence_open(seq->relid, NoLock);
1120 : : }
1121 : :
1122 : : /*
1123 : : * Creates the hash table for storing sequence data
1124 : : */
1125 : : static void
1126 : 441 : create_seq_hashtable(void)
1127 : : {
1128 : : HASHCTL ctl;
1129 : :
1130 : 441 : ctl.keysize = sizeof(Oid);
1131 : 441 : ctl.entrysize = sizeof(SeqTableData);
1132 : :
1133 : 441 : seqhashtab = hash_create("Sequence values", 16, &ctl,
1134 : : HASH_ELEM | HASH_BLOBS);
1135 : 441 : }
1136 : :
1137 : : /*
1138 : : * Given a relation OID, open and lock the sequence. p_elm and p_rel are
1139 : : * output parameters.
1140 : : */
1141 : : static void
1142 : 288473 : init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel)
1143 : : {
1144 : : SeqTable elm;
1145 : : Relation seqrel;
1146 : : bool found;
1147 : :
1148 : : /* Find or create a hash table entry for this sequence */
1149 [ + + ]: 288473 : if (seqhashtab == NULL)
1150 : 441 : create_seq_hashtable();
1151 : :
1152 : 288473 : elm = (SeqTable) hash_search(seqhashtab, &relid, HASH_ENTER, &found);
1153 : :
1154 : : /*
1155 : : * Initialize the new hash table entry if it did not exist already.
1156 : : *
1157 : : * NOTE: seqhashtab entries are stored for the life of a backend (unless
1158 : : * explicitly discarded with DISCARD). If the sequence itself is deleted
1159 : : * then the entry becomes wasted memory, but it's small enough that this
1160 : : * should not matter.
1161 : : */
1162 [ + + ]: 288473 : if (!found)
1163 : : {
1164 : : /* relid already filled in */
1165 : 1349 : elm->filenumber = InvalidRelFileNumber;
1166 : 1349 : elm->lxid = InvalidLocalTransactionId;
1167 : 1349 : elm->last_valid = false;
1168 : 1349 : elm->last = elm->cached = 0;
1169 : : }
1170 : :
1171 : : /*
1172 : : * Open the sequence relation.
1173 : : */
1174 : 288473 : seqrel = lock_and_open_sequence(elm);
1175 : :
1176 : : /*
1177 : : * If the sequence has been transactionally replaced since we last saw it,
1178 : : * discard any cached-but-unissued values. We do not touch the currval()
1179 : : * state, however.
1180 : : */
1181 [ + + ]: 288469 : if (seqrel->rd_rel->relfilenode != elm->filenumber)
1182 : : {
1183 : 1441 : elm->filenumber = seqrel->rd_rel->relfilenode;
1184 : 1441 : elm->cached = elm->last;
1185 : : }
1186 : :
1187 : : /* Return results */
1188 : 288469 : *p_elm = elm;
1189 : 288469 : *p_rel = seqrel;
1190 : 288469 : }
1191 : :
1192 : :
1193 : : /*
1194 : : * Given an opened sequence relation, lock the page buffer and find the tuple
1195 : : *
1196 : : * *buf receives the reference to the pinned-and-ex-locked buffer
1197 : : * *seqdatatuple receives the reference to the sequence tuple proper
1198 : : * (this arg should point to a local variable of type HeapTupleData)
1199 : : *
1200 : : * Function's return value points to the data payload of the tuple
1201 : : */
1202 : : static Form_pg_sequence_data
1203 : 289025 : read_seq_tuple(Relation rel, Buffer *buf, HeapTuple seqdatatuple)
1204 : : {
1205 : : Page page;
1206 : : ItemId lp;
1207 : : sequence_magic *sm;
1208 : : Form_pg_sequence_data seq;
1209 : :
1210 : 289025 : *buf = ReadBuffer(rel, 0);
1211 : 289025 : LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);
1212 : :
1213 : 289025 : page = BufferGetPage(*buf);
1214 : 289025 : sm = (sequence_magic *) PageGetSpecialPointer(page);
1215 : :
1216 [ - + ]: 289025 : if (sm->magic != SEQ_MAGIC)
1217 [ # # ]: 0 : elog(ERROR, "bad magic number in sequence \"%s\": %08X",
1218 : : RelationGetRelationName(rel), sm->magic);
1219 : :
1220 : 289025 : lp = PageGetItemId(page, FirstOffsetNumber);
1221 : : Assert(ItemIdIsNormal(lp));
1222 : :
1223 : : /* Note we currently only bother to set these two fields of *seqdatatuple */
1224 : 289025 : seqdatatuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1225 : 289025 : seqdatatuple->t_len = ItemIdGetLength(lp);
1226 : :
1227 : : /*
1228 : : * Previous releases of Postgres neglected to prevent SELECT FOR UPDATE on
1229 : : * a sequence, which would leave a non-frozen XID in the sequence tuple's
1230 : : * xmax, which eventually leads to clog access failures or worse. If we
1231 : : * see this has happened, clean up after it. We treat this like a hint
1232 : : * bit update, ie, don't bother to WAL-log it, since we can certainly do
1233 : : * this again if the update gets lost.
1234 : : */
1235 : : Assert(!(seqdatatuple->t_data->t_infomask & HEAP_XMAX_IS_MULTI));
1236 [ - + ]: 289025 : if (HeapTupleHeaderGetRawXmax(seqdatatuple->t_data) != InvalidTransactionId)
1237 : : {
1238 : 0 : HeapTupleHeaderSetXmax(seqdatatuple->t_data, InvalidTransactionId);
1239 : 0 : seqdatatuple->t_data->t_infomask &= ~HEAP_XMAX_COMMITTED;
1240 : 0 : seqdatatuple->t_data->t_infomask |= HEAP_XMAX_INVALID;
1241 : 0 : MarkBufferDirtyHint(*buf, true);
1242 : : }
1243 : :
1244 : 289025 : seq = (Form_pg_sequence_data) GETSTRUCT(seqdatatuple);
1245 : :
1246 : 289025 : return seq;
1247 : : }
1248 : :
1249 : : /*
1250 : : * init_params: process the options list of CREATE or ALTER SEQUENCE, and
1251 : : * store the values into appropriate fields of seqform, for changes that go
1252 : : * into the pg_sequence catalog, and fields for changes to the sequence
1253 : : * relation itself (*is_called, *last_value and *reset_state). Set
1254 : : * *need_seq_rewrite to true if we changed any parameters that require
1255 : : * rewriting the sequence's relation (interesting for ALTER SEQUENCE). Also
1256 : : * set *owned_by to any OWNED BY option, or to NIL if there is none. Set
1257 : : * *reset_state to true if the internal state of the sequence needs to be
1258 : : * reset, affecting future nextval() calls, for example with WAL logging.
1259 : : *
1260 : : * If isInit is true, fill any unspecified options with default values;
1261 : : * otherwise, do not change existing options that aren't explicitly overridden.
1262 : : *
1263 : : * Note: we force a sequence rewrite whenever we change parameters that affect
1264 : : * generation of future sequence values, even if the metadata per se is not
1265 : : * changed. This allows ALTER SEQUENCE to behave transactionally. Currently,
1266 : : * the only option that doesn't cause that is OWNED BY. It's *necessary* for
1267 : : * ALTER SEQUENCE OWNED BY to not rewrite the sequence, because that would
1268 : : * break pg_upgrade by causing unwanted changes in the sequence's
1269 : : * relfilenumber.
1270 : : */
1271 : : static void
1272 : 2274 : init_params(ParseState *pstate, List *options, bool for_identity,
1273 : : bool isInit,
1274 : : Form_pg_sequence seqform,
1275 : : int64 *last_value,
1276 : : bool *reset_state,
1277 : : bool *is_called,
1278 : : bool *need_seq_rewrite,
1279 : : List **owned_by)
1280 : : {
1281 : 2274 : DefElem *as_type = NULL;
1282 : 2274 : DefElem *start_value = NULL;
1283 : 2274 : DefElem *restart_value = NULL;
1284 : 2274 : DefElem *increment_by = NULL;
1285 : 2274 : DefElem *max_value = NULL;
1286 : 2274 : DefElem *min_value = NULL;
1287 : 2274 : DefElem *cache_value = NULL;
1288 : 2274 : DefElem *is_cycled = NULL;
1289 : : ListCell *option;
1290 : 2274 : bool reset_max_value = false;
1291 : 2274 : bool reset_min_value = false;
1292 : :
1293 : 2274 : *need_seq_rewrite = false;
1294 : 2274 : *owned_by = NIL;
1295 : :
1296 [ + + + + : 4855 : foreach(option, options)
+ + ]
1297 : : {
1298 : 2581 : DefElem *defel = (DefElem *) lfirst(option);
1299 : :
1300 [ + + ]: 2581 : if (strcmp(defel->defname, "as") == 0)
1301 : : {
1302 [ - + ]: 986 : if (as_type)
1303 : 0 : errorConflictingDefElem(defel, pstate);
1304 : 986 : as_type = defel;
1305 : 986 : *need_seq_rewrite = true;
1306 : : }
1307 [ + + ]: 1595 : else if (strcmp(defel->defname, "increment") == 0)
1308 : : {
1309 [ - + ]: 165 : if (increment_by)
1310 : 0 : errorConflictingDefElem(defel, pstate);
1311 : 165 : increment_by = defel;
1312 : 165 : *need_seq_rewrite = true;
1313 : : }
1314 [ + + ]: 1430 : else if (strcmp(defel->defname, "start") == 0)
1315 : : {
1316 [ - + ]: 156 : if (start_value)
1317 : 0 : errorConflictingDefElem(defel, pstate);
1318 : 156 : start_value = defel;
1319 : 156 : *need_seq_rewrite = true;
1320 : : }
1321 [ + + ]: 1274 : else if (strcmp(defel->defname, "restart") == 0)
1322 : : {
1323 [ - + ]: 63 : if (restart_value)
1324 : 0 : errorConflictingDefElem(defel, pstate);
1325 : 63 : restart_value = defel;
1326 : 63 : *need_seq_rewrite = true;
1327 : : }
1328 [ + + ]: 1211 : else if (strcmp(defel->defname, "maxvalue") == 0)
1329 : : {
1330 [ - + ]: 116 : if (max_value)
1331 : 0 : errorConflictingDefElem(defel, pstate);
1332 : 116 : max_value = defel;
1333 : 116 : *need_seq_rewrite = true;
1334 : : }
1335 [ + + ]: 1095 : else if (strcmp(defel->defname, "minvalue") == 0)
1336 : : {
1337 [ - + ]: 116 : if (min_value)
1338 : 0 : errorConflictingDefElem(defel, pstate);
1339 : 116 : min_value = defel;
1340 : 116 : *need_seq_rewrite = true;
1341 : : }
1342 [ + + ]: 979 : else if (strcmp(defel->defname, "cache") == 0)
1343 : : {
1344 [ - + ]: 90 : if (cache_value)
1345 : 0 : errorConflictingDefElem(defel, pstate);
1346 : 90 : cache_value = defel;
1347 : 90 : *need_seq_rewrite = true;
1348 : : }
1349 [ + + ]: 889 : else if (strcmp(defel->defname, "cycle") == 0)
1350 : : {
1351 [ - + ]: 31 : if (is_cycled)
1352 : 0 : errorConflictingDefElem(defel, pstate);
1353 : 31 : is_cycled = defel;
1354 : 31 : *need_seq_rewrite = true;
1355 : : }
1356 [ + - ]: 858 : else if (strcmp(defel->defname, "owned_by") == 0)
1357 : : {
1358 [ - + ]: 858 : if (*owned_by)
1359 : 0 : errorConflictingDefElem(defel, pstate);
1360 : 858 : *owned_by = defGetQualifiedName(defel);
1361 : : }
1362 [ # # ]: 0 : else if (strcmp(defel->defname, "sequence_name") == 0)
1363 : : {
1364 : : /*
1365 : : * The parser allows this, but it is only for identity columns, in
1366 : : * which case it is filtered out in parse_utilcmd.c. We only get
1367 : : * here if someone puts it into a CREATE SEQUENCE, where it'd be
1368 : : * redundant. (The same is true for the equally-nonstandard
1369 : : * LOGGED and UNLOGGED options, but for those, the default error
1370 : : * below seems sufficient.)
1371 : : */
1372 [ # # ]: 0 : ereport(ERROR,
1373 : : (errcode(ERRCODE_SYNTAX_ERROR),
1374 : : errmsg("invalid sequence option SEQUENCE NAME"),
1375 : : parser_errposition(pstate, defel->location)));
1376 : : }
1377 : : else
1378 [ # # ]: 0 : elog(ERROR, "option \"%s\" not recognized",
1379 : : defel->defname);
1380 : : }
1381 : :
1382 : : /*
1383 : : * We must reset the state of the sequence when isInit or when changing
1384 : : * any parameters that would affect future nextval allocations.
1385 : : */
1386 [ + + ]: 2274 : if (isInit)
1387 : 1281 : *reset_state = true;
1388 : :
1389 : : /* AS type */
1390 [ + + ]: 2274 : if (as_type != NULL)
1391 : : {
1392 : 986 : Oid newtypid = typenameTypeId(pstate, defGetTypeName(as_type));
1393 : :
1394 [ + + + + ]: 982 : if (newtypid != INT2OID &&
1395 [ + + ]: 93 : newtypid != INT4OID &&
1396 : : newtypid != INT8OID)
1397 [ + - + + ]: 16 : ereport(ERROR,
1398 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1399 : : for_identity
1400 : : ? errmsg("identity column type must be smallint, integer, or bigint")
1401 : : : errmsg("sequence type must be smallint, integer, or bigint")));
1402 : :
1403 [ + + ]: 966 : if (!isInit)
1404 : : {
1405 : : /*
1406 : : * When changing type and the old sequence min/max values were the
1407 : : * min/max of the old type, adjust sequence min/max values to
1408 : : * min/max of new type. (Otherwise, the user chose explicit
1409 : : * min/max values, which we'll leave alone.)
1410 : : */
1411 [ + + + + ]: 60 : if ((seqform->seqtypid == INT2OID && seqform->seqmax == PG_INT16_MAX) ||
1412 [ + + + + ]: 44 : (seqform->seqtypid == INT4OID && seqform->seqmax == PG_INT32_MAX) ||
1413 [ + + + - ]: 24 : (seqform->seqtypid == INT8OID && seqform->seqmax == PG_INT64_MAX))
1414 : 44 : reset_max_value = true;
1415 [ + + + + ]: 60 : if ((seqform->seqtypid == INT2OID && seqform->seqmin == PG_INT16_MIN) ||
1416 [ + + + + ]: 48 : (seqform->seqtypid == INT4OID && seqform->seqmin == PG_INT32_MIN) ||
1417 [ + + - + ]: 44 : (seqform->seqtypid == INT8OID && seqform->seqmin == PG_INT64_MIN))
1418 : 16 : reset_min_value = true;
1419 : : }
1420 : :
1421 : 966 : seqform->seqtypid = newtypid;
1422 : : }
1423 [ + + ]: 1288 : else if (isInit)
1424 : : {
1425 : 359 : seqform->seqtypid = INT8OID;
1426 : : }
1427 : :
1428 : : /* INCREMENT BY */
1429 [ + + ]: 2254 : if (increment_by != NULL)
1430 : : {
1431 : 165 : seqform->seqincrement = defGetInt64(increment_by);
1432 [ + + ]: 165 : if (seqform->seqincrement == 0)
1433 [ + - ]: 4 : ereport(ERROR,
1434 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1435 : : errmsg("INCREMENT must not be zero")));
1436 : 161 : *reset_state = true;
1437 : : }
1438 [ + + ]: 2089 : else if (isInit)
1439 : : {
1440 : 1135 : seqform->seqincrement = 1;
1441 : : }
1442 : :
1443 : : /* CYCLE */
1444 [ + + ]: 2250 : if (is_cycled != NULL)
1445 : : {
1446 : 31 : seqform->seqcycle = boolVal(is_cycled->arg);
1447 : : Assert(BoolIsValid(seqform->seqcycle));
1448 : 31 : *reset_state = true;
1449 : : }
1450 [ + + ]: 2219 : else if (isInit)
1451 : : {
1452 : 1251 : seqform->seqcycle = false;
1453 : : }
1454 : :
1455 : : /* MAXVALUE (null arg means NO MAXVALUE) */
1456 [ + + + + ]: 2250 : if (max_value != NULL && max_value->arg)
1457 : : {
1458 : 47 : seqform->seqmax = defGetInt64(max_value);
1459 : 47 : *reset_state = true;
1460 : : }
1461 [ + + + - : 2203 : else if (isInit || max_value != NULL || reset_max_value)
+ + ]
1462 : : {
1463 [ + + + + ]: 1277 : if (seqform->seqincrement > 0 || reset_max_value)
1464 : : {
1465 : : /* ascending seq */
1466 [ + + ]: 1254 : if (seqform->seqtypid == INT2OID)
1467 : 48 : seqform->seqmax = PG_INT16_MAX;
1468 [ + + ]: 1206 : else if (seqform->seqtypid == INT4OID)
1469 : 801 : seqform->seqmax = PG_INT32_MAX;
1470 : : else
1471 : 405 : seqform->seqmax = PG_INT64_MAX;
1472 : : }
1473 : : else
1474 : 23 : seqform->seqmax = -1; /* descending seq */
1475 : 1277 : *reset_state = true;
1476 : : }
1477 : :
1478 : : /* Validate maximum value. No need to check INT8 as seqmax is an int64 */
1479 [ + + + - : 2250 : if ((seqform->seqtypid == INT2OID && (seqform->seqmax < PG_INT16_MIN || seqform->seqmax > PG_INT16_MAX))
+ + ]
1480 [ + + + - : 2242 : || (seqform->seqtypid == INT4OID && (seqform->seqmax < PG_INT32_MIN || seqform->seqmax > PG_INT32_MAX)))
- + ]
1481 [ + - ]: 8 : ereport(ERROR,
1482 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1483 : : errmsg("MAXVALUE (%" PRId64 ") is out of range for sequence data type %s",
1484 : : seqform->seqmax,
1485 : : format_type_be(seqform->seqtypid))));
1486 : :
1487 : : /* MINVALUE (null arg means NO MINVALUE) */
1488 [ + + + + ]: 2242 : if (min_value != NULL && min_value->arg)
1489 : : {
1490 : 47 : seqform->seqmin = defGetInt64(min_value);
1491 : 47 : *reset_state = true;
1492 : : }
1493 [ + + + - : 2195 : else if (isInit || min_value != NULL || reset_min_value)
+ + ]
1494 : : {
1495 [ + + + + ]: 1243 : if (seqform->seqincrement < 0 || reset_min_value)
1496 : : {
1497 : : /* descending seq */
1498 [ + + ]: 40 : if (seqform->seqtypid == INT2OID)
1499 : 13 : seqform->seqmin = PG_INT16_MIN;
1500 [ + + ]: 27 : else if (seqform->seqtypid == INT4OID)
1501 : 18 : seqform->seqmin = PG_INT32_MIN;
1502 : : else
1503 : 9 : seqform->seqmin = PG_INT64_MIN;
1504 : : }
1505 : : else
1506 : 1203 : seqform->seqmin = 1; /* ascending seq */
1507 : 1243 : *reset_state = true;
1508 : : }
1509 : :
1510 : : /* Validate minimum value. No need to check INT8 as seqmin is an int64 */
1511 [ + + + + : 2242 : if ((seqform->seqtypid == INT2OID && (seqform->seqmin < PG_INT16_MIN || seqform->seqmin > PG_INT16_MAX))
+ - ]
1512 [ + + + - : 2234 : || (seqform->seqtypid == INT4OID && (seqform->seqmin < PG_INT32_MIN || seqform->seqmin > PG_INT32_MAX)))
- + ]
1513 [ + - ]: 8 : ereport(ERROR,
1514 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1515 : : errmsg("MINVALUE (%" PRId64 ") is out of range for sequence data type %s",
1516 : : seqform->seqmin,
1517 : : format_type_be(seqform->seqtypid))));
1518 : :
1519 : : /* crosscheck min/max */
1520 [ + + ]: 2234 : if (seqform->seqmin >= seqform->seqmax)
1521 [ + - ]: 8 : ereport(ERROR,
1522 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1523 : : errmsg("MINVALUE (%" PRId64 ") must be less than MAXVALUE (%" PRId64 ")",
1524 : : seqform->seqmin,
1525 : : seqform->seqmax)));
1526 : :
1527 : : /* START WITH */
1528 [ + + ]: 2226 : if (start_value != NULL)
1529 : : {
1530 : 156 : seqform->seqstart = defGetInt64(start_value);
1531 : : }
1532 [ + + ]: 2070 : else if (isInit)
1533 : : {
1534 [ + + ]: 1111 : if (seqform->seqincrement > 0)
1535 : 1095 : seqform->seqstart = seqform->seqmin; /* ascending seq */
1536 : : else
1537 : 16 : seqform->seqstart = seqform->seqmax; /* descending seq */
1538 : : }
1539 : :
1540 : : /* crosscheck START */
1541 [ + + ]: 2226 : if (seqform->seqstart < seqform->seqmin)
1542 [ + - ]: 4 : ereport(ERROR,
1543 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1544 : : errmsg("START value (%" PRId64 ") cannot be less than MINVALUE (%" PRId64 ")",
1545 : : seqform->seqstart,
1546 : : seqform->seqmin)));
1547 [ + + ]: 2222 : if (seqform->seqstart > seqform->seqmax)
1548 [ + - ]: 4 : ereport(ERROR,
1549 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1550 : : errmsg("START value (%" PRId64 ") cannot be greater than MAXVALUE (%" PRId64 ")",
1551 : : seqform->seqstart,
1552 : : seqform->seqmax)));
1553 : :
1554 : : /* RESTART [WITH] */
1555 [ + + ]: 2218 : if (restart_value != NULL)
1556 : : {
1557 [ + + ]: 63 : if (restart_value->arg != NULL)
1558 : 43 : *last_value = defGetInt64(restart_value);
1559 : : else
1560 : 20 : *last_value = seqform->seqstart;
1561 : 63 : *is_called = false;
1562 : 63 : *reset_state = true;
1563 : : }
1564 [ + + ]: 2155 : else if (isInit)
1565 : : {
1566 : 1237 : *last_value = seqform->seqstart;
1567 : 1237 : *is_called = false;
1568 : : }
1569 : :
1570 : : /* crosscheck RESTART (or current value, if changing MIN/MAX) */
1571 [ + + ]: 2218 : if (*last_value < seqform->seqmin)
1572 [ + - ]: 4 : ereport(ERROR,
1573 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1574 : : errmsg("RESTART value (%" PRId64 ") cannot be less than MINVALUE (%" PRId64 ")",
1575 : : *last_value,
1576 : : seqform->seqmin)));
1577 [ + + ]: 2214 : if (*last_value > seqform->seqmax)
1578 [ + - ]: 4 : ereport(ERROR,
1579 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1580 : : errmsg("RESTART value (%" PRId64 ") cannot be greater than MAXVALUE (%" PRId64 ")",
1581 : : *last_value,
1582 : : seqform->seqmax)));
1583 : :
1584 : : /* CACHE */
1585 [ + + ]: 2210 : if (cache_value != NULL)
1586 : : {
1587 : 90 : seqform->seqcache = defGetInt64(cache_value);
1588 [ + + ]: 90 : if (seqform->seqcache <= 0)
1589 [ + - ]: 4 : ereport(ERROR,
1590 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1591 : : errmsg("CACHE (%" PRId64 ") must be greater than zero",
1592 : : seqform->seqcache)));
1593 : 86 : *reset_state = true;
1594 : : }
1595 [ + + ]: 2120 : else if (isInit)
1596 : : {
1597 : 1148 : seqform->seqcache = 1;
1598 : : }
1599 : 2206 : }
1600 : :
1601 : : /*
1602 : : * Process an OWNED BY option for CREATE/ALTER SEQUENCE
1603 : : *
1604 : : * Ownership permissions on the sequence are already checked,
1605 : : * but if we are establishing a new owned-by dependency, we must
1606 : : * enforce that the referenced table has the same owner and namespace
1607 : : * as the sequence.
1608 : : */
1609 : : static void
1610 : 858 : process_owned_by(Relation seqrel, List *owned_by, bool for_identity)
1611 : : {
1612 : : DependencyType deptype;
1613 : : int nnames;
1614 : : Relation tablerel;
1615 : : AttrNumber attnum;
1616 : :
1617 [ + + ]: 858 : deptype = for_identity ? DEPENDENCY_INTERNAL : DEPENDENCY_AUTO;
1618 : :
1619 : 858 : nnames = list_length(owned_by);
1620 : : Assert(nnames > 0);
1621 [ + + ]: 858 : if (nnames == 1)
1622 : : {
1623 : : /* Must be OWNED BY NONE */
1624 [ + + ]: 8 : if (strcmp(strVal(linitial(owned_by)), "none") != 0)
1625 [ + - ]: 4 : ereport(ERROR,
1626 : : (errcode(ERRCODE_SYNTAX_ERROR),
1627 : : errmsg("invalid OWNED BY option"),
1628 : : errhint("Specify OWNED BY table.column or OWNED BY NONE.")));
1629 : 4 : tablerel = NULL;
1630 : 4 : attnum = 0;
1631 : : }
1632 : : else
1633 : : {
1634 : : List *relname;
1635 : : char *attrname;
1636 : : RangeVar *rel;
1637 : :
1638 : : /* Separate relname and attr name */
1639 : 850 : relname = list_copy_head(owned_by, nnames - 1);
1640 : 850 : attrname = strVal(llast(owned_by));
1641 : :
1642 : : /* Open and lock rel to ensure it won't go away meanwhile */
1643 : 850 : rel = makeRangeVarFromNameList(relname);
1644 : 850 : tablerel = relation_openrv(rel, AccessShareLock);
1645 : :
1646 : : /* Must be a regular or foreign table */
1647 [ + + ]: 850 : if (!(tablerel->rd_rel->relkind == RELKIND_RELATION ||
1648 [ + + ]: 34 : tablerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE ||
1649 [ + - ]: 29 : tablerel->rd_rel->relkind == RELKIND_VIEW ||
1650 [ + + ]: 29 : tablerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
1651 [ + - ]: 4 : ereport(ERROR,
1652 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1653 : : errmsg("sequence cannot be owned by relation \"%s\"",
1654 : : RelationGetRelationName(tablerel)),
1655 : : errdetail_relkind_not_supported(tablerel->rd_rel->relkind)));
1656 : :
1657 : : /* We insist on same owner and schema */
1658 [ - + ]: 846 : if (seqrel->rd_rel->relowner != tablerel->rd_rel->relowner)
1659 [ # # ]: 0 : ereport(ERROR,
1660 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1661 : : errmsg("sequence must have same owner as table it is linked to")));
1662 [ + + ]: 846 : if (RelationGetNamespace(seqrel) != RelationGetNamespace(tablerel))
1663 [ + - ]: 4 : ereport(ERROR,
1664 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1665 : : errmsg("sequence must be in same schema as table it is linked to")));
1666 : :
1667 : : /* Now, fetch the attribute number from the system cache */
1668 : 842 : attnum = get_attnum(RelationGetRelid(tablerel), attrname);
1669 [ + + ]: 842 : if (attnum == InvalidAttrNumber)
1670 [ + - ]: 4 : ereport(ERROR,
1671 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
1672 : : errmsg("column \"%s\" of relation \"%s\" does not exist",
1673 : : attrname, RelationGetRelationName(tablerel))));
1674 : : }
1675 : :
1676 : : /*
1677 : : * Catch user explicitly running OWNED BY on identity sequence.
1678 : : */
1679 [ + + ]: 842 : if (deptype == DEPENDENCY_AUTO)
1680 : : {
1681 : : Oid tableId;
1682 : : int32 colId;
1683 : :
1684 [ + + ]: 562 : if (sequenceIsOwned(RelationGetRelid(seqrel), DEPENDENCY_INTERNAL, &tableId, &colId))
1685 [ + - ]: 4 : ereport(ERROR,
1686 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1687 : : errmsg("cannot change ownership of identity sequence"),
1688 : : errdetail("Sequence \"%s\" is linked to table \"%s\".",
1689 : : RelationGetRelationName(seqrel),
1690 : : get_rel_name(tableId))));
1691 : : }
1692 : :
1693 : : /*
1694 : : * OK, we are ready to update pg_depend. First remove any existing
1695 : : * dependencies for the sequence, then optionally add a new one.
1696 : : */
1697 : 838 : deleteDependencyRecordsForClass(RelationRelationId, RelationGetRelid(seqrel),
1698 : : RelationRelationId, deptype);
1699 : :
1700 [ + - ]: 838 : if (tablerel)
1701 : : {
1702 : : ObjectAddress refobject,
1703 : : depobject;
1704 : :
1705 : 838 : refobject.classId = RelationRelationId;
1706 : 838 : refobject.objectId = RelationGetRelid(tablerel);
1707 : 838 : refobject.objectSubId = attnum;
1708 : 838 : depobject.classId = RelationRelationId;
1709 : 838 : depobject.objectId = RelationGetRelid(seqrel);
1710 : 838 : depobject.objectSubId = 0;
1711 : 838 : recordDependencyOn(&depobject, &refobject, deptype);
1712 : : }
1713 : :
1714 : : /* Done, but hold lock until commit */
1715 [ + - ]: 838 : if (tablerel)
1716 : 838 : relation_close(tablerel, NoLock);
1717 : 838 : }
1718 : :
1719 : :
1720 : : /*
1721 : : * Return sequence parameters in a list of the form created by the parser.
1722 : : */
1723 : : List *
1724 : 8 : sequence_options(Oid relid)
1725 : : {
1726 : : HeapTuple pgstuple;
1727 : : Form_pg_sequence pgsform;
1728 : 8 : List *options = NIL;
1729 : :
1730 : 8 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
1731 [ - + ]: 8 : if (!HeapTupleIsValid(pgstuple))
1732 [ # # ]: 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
1733 : 8 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
1734 : :
1735 : : /* Use makeFloat() for 64-bit integers, like gram.y does. */
1736 : 8 : options = lappend(options,
1737 : 8 : makeDefElem("cache", (Node *) makeFloat(psprintf(INT64_FORMAT, pgsform->seqcache)), -1));
1738 : 8 : options = lappend(options,
1739 : 8 : makeDefElem("cycle", (Node *) makeBoolean(pgsform->seqcycle), -1));
1740 : 8 : options = lappend(options,
1741 : 8 : makeDefElem("increment", (Node *) makeFloat(psprintf(INT64_FORMAT, pgsform->seqincrement)), -1));
1742 : 8 : options = lappend(options,
1743 : 8 : makeDefElem("maxvalue", (Node *) makeFloat(psprintf(INT64_FORMAT, pgsform->seqmax)), -1));
1744 : 8 : options = lappend(options,
1745 : 8 : makeDefElem("minvalue", (Node *) makeFloat(psprintf(INT64_FORMAT, pgsform->seqmin)), -1));
1746 : 8 : options = lappend(options,
1747 : 8 : makeDefElem("start", (Node *) makeFloat(psprintf(INT64_FORMAT, pgsform->seqstart)), -1));
1748 : :
1749 : 8 : ReleaseSysCache(pgstuple);
1750 : :
1751 : 8 : return options;
1752 : : }
1753 : :
1754 : : /*
1755 : : * Return sequence parameters (formerly for use by information schema)
1756 : : */
1757 : : Datum
1758 : 4 : pg_sequence_parameters(PG_FUNCTION_ARGS)
1759 : : {
1760 : 4 : Oid relid = PG_GETARG_OID(0);
1761 : : TupleDesc tupdesc;
1762 : : Datum values[7];
1763 : : bool isnull[7];
1764 : : HeapTuple pgstuple;
1765 : : Form_pg_sequence pgsform;
1766 : :
1767 [ - + ]: 4 : if (pg_class_aclcheck(relid, GetUserId(), ACL_SELECT | ACL_UPDATE | ACL_USAGE) != ACLCHECK_OK)
1768 [ # # ]: 0 : ereport(ERROR,
1769 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1770 : : errmsg("permission denied for sequence %s",
1771 : : get_rel_name(relid))));
1772 : :
1773 [ - + ]: 4 : if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1774 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
1775 : :
1776 : 4 : memset(isnull, 0, sizeof(isnull));
1777 : :
1778 : 4 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
1779 [ - + ]: 4 : if (!HeapTupleIsValid(pgstuple))
1780 [ # # ]: 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
1781 : 4 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
1782 : :
1783 : 4 : values[0] = Int64GetDatum(pgsform->seqstart);
1784 : 4 : values[1] = Int64GetDatum(pgsform->seqmin);
1785 : 4 : values[2] = Int64GetDatum(pgsform->seqmax);
1786 : 4 : values[3] = Int64GetDatum(pgsform->seqincrement);
1787 : 4 : values[4] = BoolGetDatum(pgsform->seqcycle);
1788 : 4 : values[5] = Int64GetDatum(pgsform->seqcache);
1789 : 4 : values[6] = ObjectIdGetDatum(pgsform->seqtypid);
1790 : :
1791 : 4 : ReleaseSysCache(pgstuple);
1792 : :
1793 : 4 : return HeapTupleGetDatum(heap_form_tuple(tupdesc, values, isnull));
1794 : : }
1795 : :
1796 : :
1797 : : /*
1798 : : * Return the sequence tuple along with its page LSN.
1799 : : *
1800 : : * This is primarily used by pg_dump to efficiently collect sequence data
1801 : : * without querying each sequence individually, and is also leveraged by
1802 : : * logical replication while synchronizing sequences.
1803 : : */
1804 : : Datum
1805 : 680 : pg_get_sequence_data(PG_FUNCTION_ARGS)
1806 : : {
1807 : : #define PG_GET_SEQUENCE_DATA_COLS 3
1808 : 680 : Oid relid = PG_GETARG_OID(0);
1809 : : Relation seqrel;
1810 : 680 : Datum values[PG_GET_SEQUENCE_DATA_COLS] = {0};
1811 : 680 : bool isnull[PG_GET_SEQUENCE_DATA_COLS] = {0};
1812 : : TupleDesc resultTupleDesc;
1813 : : HeapTuple resultHeapTuple;
1814 : : Datum result;
1815 : :
1816 : 680 : resultTupleDesc = CreateTemplateTupleDesc(PG_GET_SEQUENCE_DATA_COLS);
1817 : 680 : TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "last_value",
1818 : : INT8OID, -1, 0);
1819 : 680 : TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "is_called",
1820 : : BOOLOID, -1, 0);
1821 : 680 : TupleDescInitEntry(resultTupleDesc, (AttrNumber) 3, "page_lsn",
1822 : : LSNOID, -1, 0);
1823 : 680 : TupleDescFinalize(resultTupleDesc);
1824 : 680 : resultTupleDesc = BlessTupleDesc(resultTupleDesc);
1825 : :
1826 : 680 : seqrel = try_relation_open(relid, AccessShareLock);
1827 : :
1828 : : /*
1829 : : * Return all NULLs for missing sequences, sequences for which we lack
1830 : : * privileges, other sessions' temporary sequences, and unlogged sequences
1831 : : * on standbys.
1832 : : */
1833 [ + + + - : 1359 : if (seqrel && seqrel->rd_rel->relkind == RELKIND_SEQUENCE &&
+ + ]
1834 : 679 : pg_class_aclcheck(relid, GetUserId(), ACL_SELECT) == ACLCHECK_OK &&
1835 [ - + - - ]: 668 : !RELATION_IS_OTHER_TEMP(seqrel) &&
1836 [ + + + + ]: 668 : (RelationIsPermanent(seqrel) || !RecoveryInProgress()))
1837 : 658 : {
1838 : : Buffer buf;
1839 : : HeapTupleData seqtuple;
1840 : : Form_pg_sequence_data seq;
1841 : : Page page;
1842 : :
1843 : 658 : seq = read_seq_tuple(seqrel, &buf, &seqtuple);
1844 : 658 : page = BufferGetPage(buf);
1845 : :
1846 : 658 : values[0] = Int64GetDatum(seq->last_value);
1847 : 658 : values[1] = BoolGetDatum(seq->is_called);
1848 : 658 : values[2] = LSNGetDatum(PageGetLSN(page));
1849 : :
1850 : 658 : UnlockReleaseBuffer(buf);
1851 : : }
1852 : : else
1853 : 22 : memset(isnull, true, sizeof(isnull));
1854 : :
1855 [ + + ]: 680 : if (seqrel)
1856 : 679 : relation_close(seqrel, AccessShareLock);
1857 : :
1858 : 680 : resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
1859 : 680 : result = HeapTupleGetDatum(resultHeapTuple);
1860 : 680 : PG_RETURN_DATUM(result);
1861 : : #undef PG_GET_SEQUENCE_DATA_COLS
1862 : : }
1863 : :
1864 : :
1865 : : /*
1866 : : * Return the last value from the sequence
1867 : : *
1868 : : * Note: This has a completely different meaning than lastval().
1869 : : */
1870 : : Datum
1871 : 77 : pg_sequence_last_value(PG_FUNCTION_ARGS)
1872 : : {
1873 : 77 : Oid relid = PG_GETARG_OID(0);
1874 : : SeqTable elm;
1875 : : Relation seqrel;
1876 : 77 : bool is_called = false;
1877 : 77 : int64 result = 0;
1878 : :
1879 : : /* open and lock sequence */
1880 : 77 : init_sequence(relid, &elm, &seqrel);
1881 : :
1882 : : /*
1883 : : * We return NULL for other sessions' temporary sequences. The
1884 : : * pg_sequences system view already filters those out, but this offers a
1885 : : * defense against ERRORs in case someone invokes this function directly.
1886 : : *
1887 : : * Also, for the benefit of the pg_sequences view, we return NULL for
1888 : : * unlogged sequences on standbys and for sequences for which the current
1889 : : * user lacks privileges instead of throwing an error.
1890 : : */
1891 [ + - ]: 77 : if (pg_class_aclcheck(relid, GetUserId(), ACL_SELECT | ACL_USAGE) == ACLCHECK_OK &&
1892 [ - + - - ]: 77 : !RELATION_IS_OTHER_TEMP(seqrel) &&
1893 [ + + - + ]: 77 : (RelationIsPermanent(seqrel) || !RecoveryInProgress()))
1894 : : {
1895 : : Buffer buf;
1896 : : HeapTupleData seqtuple;
1897 : : Form_pg_sequence_data seq;
1898 : :
1899 : 76 : seq = read_seq_tuple(seqrel, &buf, &seqtuple);
1900 : :
1901 : 76 : is_called = seq->is_called;
1902 : 76 : result = seq->last_value;
1903 : :
1904 : 76 : UnlockReleaseBuffer(buf);
1905 : : }
1906 : 77 : sequence_close(seqrel, NoLock);
1907 : :
1908 [ + + ]: 77 : if (is_called)
1909 : 32 : PG_RETURN_INT64(result);
1910 : : else
1911 : 45 : PG_RETURN_NULL();
1912 : : }
1913 : :
1914 : : /*
1915 : : * Flush cached sequence information.
1916 : : */
1917 : : void
1918 : 12 : ResetSequenceCaches(void)
1919 : : {
1920 [ + + ]: 12 : if (seqhashtab)
1921 : : {
1922 : 8 : hash_destroy(seqhashtab);
1923 : 8 : seqhashtab = NULL;
1924 : : }
1925 : :
1926 : 12 : last_used_seq = NULL;
1927 : 12 : }
|