Age Owner Branch data TLA 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
3735 peter_e@gmx.net 112 :GIC 1270 : 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;
10673 bruce@momjian.us 120 : 1270 : 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 : : */
4477 heikki.linnakangas@i 137 [ + + ]: 1270 : 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 : : */
1573 tgl@sss.pgh.pa.us 146 : 6 : ObjectAddressSet(address, RelationRelationId, seqoid);
147 : 6 : checkMembershipInCurrentExtension(&address);
148 : :
149 : : /* OK to skip */
4477 heikki.linnakangas@i 150 [ + + ]: 5 : ereport(NOTICE,
151 : : (errcode(ERRCODE_DUPLICATE_TABLE),
152 : : errmsg("relation \"%s\" already exists, skipping",
153 : : seq->sequence->relname)));
4288 alvherre@alvh.no-ip. 154 : 5 : return InvalidObjectAddress;
155 : : }
156 : : }
157 : :
158 : : /* Check and set all option values */
3456 tgl@sss.pgh.pa.us 159 : 1264 : 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 : : */
10674 bruce@momjian.us 166 : 1216 : stmt->tableElts = NIL;
167 [ + + ]: 4864 : for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
168 : : {
1186 peter@eisentraut.org 169 : 3648 : ColumnDef *coldef = NULL;
170 : :
10674 bruce@momjian.us 171 [ + + + - ]: 3648 : switch (i)
172 : : {
10673 173 : 1216 : case SEQ_COL_LASTVAL:
1187 peter@eisentraut.org 174 : 1216 : coldef = makeColumnDef("last_value", INT8OID, -1, InvalidOid);
467 michael@paquier.xyz 175 : 1216 : value[i - 1] = Int64GetDatumFast(last_value);
10673 bruce@momjian.us 176 : 1216 : break;
9494 vadim4o@yahoo.com 177 : 1216 : case SEQ_COL_LOG:
1187 peter@eisentraut.org 178 : 1216 : coldef = makeColumnDef("log_cnt", INT8OID, -1, InvalidOid);
5239 tgl@sss.pgh.pa.us 179 : 1216 : value[i - 1] = Int64GetDatum((int64) 0);
9494 vadim4o@yahoo.com 180 : 1216 : break;
10673 bruce@momjian.us 181 : 1216 : case SEQ_COL_CALLED:
1187 peter@eisentraut.org 182 : 1216 : coldef = makeColumnDef("is_called", BOOLOID, -1, InvalidOid);
9235 tgl@sss.pgh.pa.us 183 : 1216 : value[i - 1] = BoolGetDatum(false);
10673 bruce@momjian.us 184 : 1216 : break;
185 : : }
186 : :
1187 peter@eisentraut.org 187 : 3648 : coldef->is_not_null = true;
188 : 3648 : null[i - 1] = false;
189 : :
10674 bruce@momjian.us 190 : 3648 : stmt->tableElts = lappend(stmt->tableElts, coldef);
191 : : }
192 : :
9018 tgl@sss.pgh.pa.us 193 : 1216 : stmt->relation = seq->sequence;
194 : 1216 : stmt->inhRelations = NIL;
10674 bruce@momjian.us 195 : 1216 : stmt->constraints = NIL;
4978 tgl@sss.pgh.pa.us 196 : 1216 : stmt->options = NIL;
8783 197 : 1216 : stmt->oncommit = ONCOMMIT_NOOP;
8174 198 : 1216 : stmt->tablespacename = NULL;
4477 heikki.linnakangas@i 199 : 1216 : stmt->if_not_exists = seq->if_not_exists;
200 : :
3643 rhaas@postgresql.org 201 : 1216 : address = DefineRelation(stmt, RELKIND_SEQUENCE, seq->ownerId, NULL, NULL);
4288 alvherre@alvh.no-ip. 202 : 1216 : seqoid = address.objectId;
5970 rhaas@postgresql.org 203 [ - + ]: 1216 : Assert(seqoid != InvalidOid);
204 : :
1006 michael@paquier.xyz 205 : 1216 : rel = sequence_open(seqoid, AccessExclusiveLock);
10315 bruce@momjian.us 206 : 1216 : tupDesc = RelationGetDescr(rel);
207 : :
208 : : /* now initialize the sequence's data */
5855 tgl@sss.pgh.pa.us 209 : 1216 : tuple = heap_form_tuple(tupDesc, value, null);
210 : 1216 : fill_seq_with_data(rel, tuple);
211 : :
212 : : /* process OWNED BY if given */
213 [ + + ]: 1216 : if (owned_by)
3523 peter_e@gmx.net 214 : 17 : process_owned_by(rel, owned_by, seq->for_identity);
215 : :
1006 michael@paquier.xyz 216 : 1200 : sequence_close(rel, NoLock);
217 : :
218 : : /* fill in pg_sequence */
2868 andres@anarazel.de 219 : 1200 : rel = table_open(SequenceRelationId, RowExclusiveLock);
3630 peter_e@gmx.net 220 : 1200 : tupDesc = RelationGetDescr(rel);
221 : :
222 : 1200 : memset(pgs_nulls, 0, sizeof(pgs_nulls));
223 : :
224 : 1200 : pgs_values[Anum_pg_sequence_seqrelid - 1] = ObjectIdGetDatum(seqoid);
3578 225 : 1200 : pgs_values[Anum_pg_sequence_seqtypid - 1] = ObjectIdGetDatum(seqform.seqtypid);
3630 226 : 1200 : pgs_values[Anum_pg_sequence_seqstart - 1] = Int64GetDatumFast(seqform.seqstart);
227 : 1200 : pgs_values[Anum_pg_sequence_seqincrement - 1] = Int64GetDatumFast(seqform.seqincrement);
228 : 1200 : pgs_values[Anum_pg_sequence_seqmax - 1] = Int64GetDatumFast(seqform.seqmax);
229 : 1200 : pgs_values[Anum_pg_sequence_seqmin - 1] = Int64GetDatumFast(seqform.seqmin);
230 : 1200 : pgs_values[Anum_pg_sequence_seqcache - 1] = Int64GetDatumFast(seqform.seqcache);
3578 231 : 1200 : pgs_values[Anum_pg_sequence_seqcycle - 1] = BoolGetDatum(seqform.seqcycle);
232 : :
3630 233 : 1200 : tuple = heap_form_tuple(tupDesc, pgs_values, pgs_nulls);
3588 alvherre@alvh.no-ip. 234 : 1200 : CatalogTupleInsert(rel, tuple);
235 : :
3630 peter_e@gmx.net 236 : 1200 : heap_freetuple(tuple);
2868 andres@anarazel.de 237 : 1200 : table_close(rel, RowExclusiveLock);
238 : :
4288 alvherre@alvh.no-ip. 239 : 1200 : 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
5855 tgl@sss.pgh.pa.us 255 : 22 : 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 : 22 : init_sequence(seq_relid, &elm, &seq_rel);
3630 peter_e@gmx.net 273 : 22 : (void) read_seq_tuple(seq_rel, &buf, &seqdatatuple);
274 : :
275 : 22 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(seq_relid));
276 [ - + ]: 22 : if (!HeapTupleIsValid(pgstuple))
3630 peter_e@gmx.net 277 [ # # ]:UIC 0 : elog(ERROR, "cache lookup failed for sequence %u", seq_relid);
3630 peter_e@gmx.net 278 :GIC 22 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
279 : 22 : startv = pgsform->seqstart;
280 : 22 : ReleaseSysCache(pgstuple);
281 : :
282 : : /*
283 : : * Copy the existing sequence tuple.
284 : : */
285 : 22 : tuple = heap_copytuple(&seqdatatuple);
286 : :
287 : : /* Now we're done with the old page */
5855 tgl@sss.pgh.pa.us 288 : 22 : UnlockReleaseBuffer(buf);
289 : :
290 : : /*
291 : : * Modify the copied tuple to execute the restart (compare the RESTART
292 : : * action in AlterSequence)
293 : : */
3630 peter_e@gmx.net 294 : 22 : seq = (Form_pg_sequence_data) GETSTRUCT(tuple);
295 : 22 : seq->last_value = startv;
5855 tgl@sss.pgh.pa.us 296 : 22 : seq->is_called = false;
5239 297 : 22 : seq->log_cnt = 0;
298 : :
299 : : /*
300 : : * Create a new storage file for the sequence.
301 : : */
1606 rhaas@postgresql.org 302 : 22 : 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 : : */
2802 andres@anarazel.de 309 [ - + ]: 22 : Assert(seq_rel->rd_rel->relfrozenxid == InvalidTransactionId);
310 [ - + ]: 22 : Assert(seq_rel->rd_rel->relminmxid == InvalidMultiXactId);
311 : :
312 : : /*
313 : : * Insert the modified tuple into the new storage file.
314 : : */
5855 tgl@sss.pgh.pa.us 315 : 22 : 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 : 22 : elm->cached = elm->last;
320 : :
1006 michael@paquier.xyz 321 : 22 : sequence_close(seq_rel, NoLock);
5855 tgl@sss.pgh.pa.us 322 : 22 : }
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 : 1409 : fill_seq_with_data(Relation rel, HeapTuple tuple)
332 : : {
1696 peter@eisentraut.org 333 : 1409 : fill_seq_fork_with_data(rel, tuple, MAIN_FORKNUM);
334 : :
335 [ + + ]: 1409 : if (rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED)
336 : : {
337 : : SMgrRelation srel;
338 : :
1000 heikki.linnakangas@i 339 : 73 : srel = smgropen(rel->rd_locator, INVALID_PROC_NUMBER);
1696 peter@eisentraut.org 340 : 73 : smgrcreate(srel, INIT_FORKNUM, false);
1606 rhaas@postgresql.org 341 : 73 : log_smgrcreate(&rel->rd_locator, INIT_FORKNUM);
1696 peter@eisentraut.org 342 : 73 : fill_seq_fork_with_data(rel, tuple, INIT_FORKNUM);
343 : 73 : FlushRelationBuffers(rel);
344 : 73 : smgrclose(srel);
345 : : }
346 : 1409 : }
347 : :
348 : : /*
349 : : * Initialize a sequence's relation fork with the specified tuple as content
350 : : */
351 : : static void
352 : 1482 : 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 : :
1193 tmunro@postgresql.or 361 : 1482 : buf = ExtendBufferedRel(BMR_REL(rel), forkNum, NULL,
362 : : EB_LOCK_FIRST | EB_SKIP_EXTENSION_LOCK);
9283 tgl@sss.pgh.pa.us 363 [ - + ]: 1482 : Assert(BufferGetBlockNumber(buf) == 0);
364 : :
3874 kgrittn@postgresql.o 365 : 1482 : page = BufferGetPage(buf);
366 : :
6712 tgl@sss.pgh.pa.us 367 : 1482 : PageInit(page, BufferGetPageSize(buf), sizeof(sequence_magic));
10674 bruce@momjian.us 368 : 1482 : sm = (sequence_magic *) PageGetSpecialPointer(page);
369 : 1482 : 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 : : */
19 andres@anarazel.de 379 : 1482 : tuple->t_data->t_infomask &= ~(HEAP_XACT_MASK);
380 : 1482 : tuple->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
381 : 1482 : 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 : : */
4603 heikki.linnakangas@i 393 : 1482 : HeapTupleHeaderSetXmin(tuple->t_data, FrozenTransactionId);
394 : 1482 : HeapTupleHeaderSetXminFrozen(tuple->t_data);
395 : 1482 : HeapTupleHeaderSetCmin(tuple->t_data, FirstCommandId);
396 : 1482 : HeapTupleHeaderSetXmax(tuple->t_data, InvalidTransactionId);
397 : 1482 : ItemPointerSet(&tuple->t_data->t_ctid, 0, FirstOffsetNumber);
398 : :
399 : : /* check the comment above nextval_internal()'s equivalent call. */
4293 andres@anarazel.de 400 [ + + + + : 1482 : if (RelationNeedsWAL(rel))
+ + - + ]
401 : 1090 : GetTopTransactionId();
402 : :
9370 vadim4o@yahoo.com 403 : 1482 : START_CRIT_SECTION();
404 : :
7547 tgl@sss.pgh.pa.us 405 : 1482 : MarkBufferDirty(buf);
406 : :
397 peter@eisentraut.org 407 : 1482 : offnum = PageAddItem(page, tuple->t_data, tuple->t_len, InvalidOffsetNumber, false, false);
4603 heikki.linnakangas@i 408 [ - + ]: 1482 : if (offnum != FirstOffsetNumber)
4603 heikki.linnakangas@i 409 [ # # ]:UIC 0 : elog(ERROR, "failed to add sequence tuple to page");
410 : :
411 : : /* XLOG stuff */
1696 peter@eisentraut.org 412 [ + + + + :GIC 1482 : if (RelationNeedsWAL(rel) || forkNum == INIT_FORKNUM)
+ + + - +
+ ]
413 : : {
414 : : xl_seq_rec xlrec;
415 : : XLogRecPtr recptr;
416 : :
4391 heikki.linnakangas@i 417 : 1163 : XLogBeginInsert();
418 : 1163 : XLogRegisterBuffer(0, buf, REGBUF_WILL_INIT);
419 : :
1606 rhaas@postgresql.org 420 : 1163 : xlrec.locator = rel->rd_locator;
421 : :
655 peter@eisentraut.org 422 : 1163 : XLogRegisterData(&xlrec, sizeof(xl_seq_rec));
423 : 1163 : XLogRegisterData(tuple->t_data, tuple->t_len);
424 : :
4391 heikki.linnakangas@i 425 : 1163 : recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG);
426 : :
9370 vadim4o@yahoo.com 427 : 1163 : PageSetLSN(page, recptr);
428 : : }
429 : :
430 [ - + ]: 1482 : END_CRIT_SECTION();
431 : :
7547 tgl@sss.pgh.pa.us 432 : 1482 : UnlockReleaseBuffer(buf);
10832 vadim4o@yahoo.com 433 : 1482 : }
434 : :
435 : : /*
436 : : * AlterSequence
437 : : *
438 : : * Modify the definition of a sequence relation
439 : : */
440 : : ObjectAddress
3735 peter_e@gmx.net 441 : 988 : 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;
467 michael@paquier.xyz 455 : 988 : 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. */
3455 peter_e@gmx.net 461 : 988 : relid = RangeVarGetRelidExtended(stmt->sequence,
462 : : ShareRowExclusiveLock,
3165 andres@anarazel.de 463 : 988 : stmt->missing_ok ? RVR_MISSING_OK : 0,
464 : : RangeVarCallbackOwnsRelation,
465 : : NULL);
5423 simon@2ndQuadrant.co 466 [ + + ]: 984 : if (relid == InvalidOid)
467 : : {
468 [ + - ]: 4 : ereport(NOTICE,
469 : : (errmsg("relation \"%s\" does not exist, skipping",
470 : : stmt->sequence->relname)));
4288 alvherre@alvh.no-ip. 471 : 4 : return InvalidObjectAddress;
472 : : }
473 : :
7727 tgl@sss.pgh.pa.us 474 : 980 : init_sequence(relid, &elm, &seqrel);
475 : :
2868 andres@anarazel.de 476 : 976 : rel = table_open(SequenceRelationId, RowExclusiveLock);
3468 477 : 976 : seqtuple = SearchSysCacheCopy1(SEQRELID,
478 : : ObjectIdGetDatum(relid));
479 [ - + ]: 976 : if (!HeapTupleIsValid(seqtuple))
3630 peter_e@gmx.net 480 [ # # ]:UIC 0 : elog(ERROR, "cache lookup failed for sequence %u",
481 : : relid);
482 : :
3468 andres@anarazel.de 483 :GIC 976 : seqform = (Form_pg_sequence) GETSTRUCT(seqtuple);
484 : :
485 : : /* lock page buffer and read tuple into new sequence structure */
486 : 976 : (void) read_seq_tuple(seqrel, &buf, &datatuple);
487 : :
488 : : /* copy the existing sequence data tuple, so it can be modified locally */
489 : 976 : newdatatuple = heap_copytuple(&datatuple);
490 : 976 : newdataform = (Form_pg_sequence_data) GETSTRUCT(newdatatuple);
467 michael@paquier.xyz 491 : 976 : last_value = newdataform->last_value;
492 : 976 : is_called = newdataform->is_called;
493 : :
3468 andres@anarazel.de 494 : 976 : UnlockReleaseBuffer(buf);
495 : :
496 : : /* Check and set new values */
3456 tgl@sss.pgh.pa.us 497 : 976 : 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 [ + + ]: 956 : 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 : : */
1606 rhaas@postgresql.org 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 : : */
2802 andres@anarazel.de 519 [ - + ]: 123 : Assert(seqrel->rd_rel->relfrozenxid == InvalidTransactionId);
520 [ - + ]: 123 : Assert(seqrel->rd_rel->relminmxid == InvalidMultiXactId);
521 : :
522 : : /*
523 : : * Insert the modified tuple into the new storage file.
524 : : */
467 michael@paquier.xyz 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;
3456 tgl@sss.pgh.pa.us 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 */
1006 michael@paquier.xyz 534 : 956 : elm->cached = elm->last;
535 : :
536 : : /* process OWNED BY if given */
7404 tgl@sss.pgh.pa.us 537 [ + + ]: 956 : if (owned_by)
3523 peter_e@gmx.net 538 : 824 : process_owned_by(seqrel, owned_by, stmt->for_identity);
539 : :
540 : : /* update the pg_sequence tuple (we could skip this in some cases...) */
3468 andres@anarazel.de 541 : 952 : CatalogTupleUpdate(rel, &seqtuple->t_self, seqtuple);
542 : :
5004 rhaas@postgresql.org 543 [ - + ]: 952 : InvokeObjectPostAlterHook(RelationRelationId, relid, 0);
544 : :
4288 alvherre@alvh.no-ip. 545 : 952 : ObjectAddressSet(address, RelationRelationId, relid);
546 : :
2868 andres@anarazel.de 547 : 952 : table_close(rel, RowExclusiveLock);
1006 michael@paquier.xyz 548 : 952 : sequence_close(seqrel, NoLock);
549 : :
4288 alvherre@alvh.no-ip. 550 : 952 : return address;
551 : : }
552 : :
553 : : void
1696 peter@eisentraut.org 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 : : */
884 noah@leadboat.com 567 : 48 : LockRelationOid(relid, AccessExclusiveLock);
1696 peter@eisentraut.org 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);
1606 rhaas@postgresql.org 575 : 48 : RelationSetNewRelfilenumber(seqrel, newrelpersistence);
1696 peter@eisentraut.org 576 : 48 : fill_seq_with_data(seqrel, &seqdatatuple);
577 : 48 : UnlockReleaseBuffer(buf);
578 : :
1006 michael@paquier.xyz 579 : 48 : sequence_close(seqrel, NoLock);
1696 peter@eisentraut.org 580 : 48 : }
581 : :
582 : : void
3630 peter_e@gmx.net 583 : 684 : DeleteSequenceTuple(Oid relid)
584 : : {
585 : : Relation rel;
586 : : HeapTuple tuple;
587 : :
2868 andres@anarazel.de 588 : 684 : rel = table_open(SequenceRelationId, RowExclusiveLock);
589 : :
3630 peter_e@gmx.net 590 : 684 : tuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
591 [ - + ]: 684 : if (!HeapTupleIsValid(tuple))
3630 peter_e@gmx.net 592 [ # # ]:UIC 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
593 : :
3587 tgl@sss.pgh.pa.us 594 :GIC 684 : CatalogTupleDelete(rel, &tuple->t_self);
595 : :
3630 peter_e@gmx.net 596 : 684 : ReleaseSysCache(tuple);
2868 andres@anarazel.de 597 : 684 : table_close(rel, RowExclusiveLock);
3630 peter_e@gmx.net 598 : 684 : }
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
9666 tgl@sss.pgh.pa.us 606 : 9 : nextval(PG_FUNCTION_ARGS)
607 : : {
3548 noah@leadboat.com 608 : 9 : text *seqin = PG_GETARG_TEXT_PP(0);
609 : : RangeVar *sequence;
610 : : Oid relid;
611 : :
7727 tgl@sss.pgh.pa.us 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 : : */
5477 rhaas@postgresql.org 622 : 9 : relid = RangeVarGetRelid(sequence, NoLock, false);
623 : :
3523 peter_e@gmx.net 624 : 9 : PG_RETURN_INT64(nextval_internal(relid, true));
625 : : }
626 : :
627 : : Datum
7727 tgl@sss.pgh.pa.us 628 : 125719 : nextval_oid(PG_FUNCTION_ARGS)
629 : : {
630 : 125719 : Oid relid = PG_GETARG_OID(0);
631 : :
3523 peter_e@gmx.net 632 : 125719 : PG_RETURN_INT64(nextval_internal(relid, true));
633 : : }
634 : :
635 : : int64
636 : 147748 : 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,
10673 bruce@momjian.us 655 : 147748 : rescnt = 0;
656 : : bool cycle;
9494 vadim4o@yahoo.com 657 : 147748 : bool logit = false;
658 : :
659 : : /* open and lock sequence */
7727 tgl@sss.pgh.pa.us 660 : 147748 : init_sequence(relid, &elm, &seqrel);
661 : :
3523 peter_e@gmx.net 662 [ + + + + ]: 273476 : if (check_permissions &&
663 : 125728 : pg_class_aclcheck(elm->relid, GetUserId(),
664 : : ACL_USAGE | ACL_UPDATE) != ACLCHECK_OK)
8532 tgl@sss.pgh.pa.us 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 */
5094 671 [ + + ]: 147744 : if (!seqrel->rd_islocaltemp)
6125 672 : 66451 : 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 : : */
4230 rhaas@postgresql.org 679 : 147740 : PreventCommandIfParallelMode("nextval()");
680 : :
3447 tgl@sss.pgh.pa.us 681 [ + + ]: 147740 : if (elm->last != elm->cached) /* some numbers were cached */
682 : : {
6974 683 [ - + ]: 8 : Assert(elm->last_valid);
684 [ - + ]: 8 : Assert(elm->increment != 0);
10674 bruce@momjian.us 685 : 8 : elm->last += elm->increment;
1006 michael@paquier.xyz 686 : 8 : sequence_close(seqrel, NoLock);
6974 tgl@sss.pgh.pa.us 687 : 8 : last_used_seq = elm;
7727 688 : 8 : return elm->last;
689 : : }
690 : :
3630 peter_e@gmx.net 691 : 147732 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
692 [ - + ]: 147732 : if (!HeapTupleIsValid(pgstuple))
3630 peter_e@gmx.net 693 [ # # ]:UIC 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
3630 peter_e@gmx.net 694 :GIC 147732 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
695 : 147732 : incby = pgsform->seqincrement;
696 : 147732 : maxv = pgsform->seqmax;
697 : 147732 : minv = pgsform->seqmin;
698 : 147732 : cache = pgsform->seqcache;
3578 699 : 147732 : cycle = pgsform->seqcycle;
3630 700 : 147732 : ReleaseSysCache(pgstuple);
701 : :
702 : : /* lock page buffer and read tuple */
703 : 147732 : seq = read_seq_tuple(seqrel, &buf, &seqdatatuple);
3874 kgrittn@postgresql.o 704 : 147732 : page = BufferGetPage(buf);
705 : :
9494 vadim4o@yahoo.com 706 : 147732 : last = next = result = seq->last_value;
3630 peter_e@gmx.net 707 : 147732 : fetch = cache;
9494 vadim4o@yahoo.com 708 : 147732 : log = seq->log_cnt;
709 : :
9235 tgl@sss.pgh.pa.us 710 [ + + ]: 147732 : if (!seq->is_called)
711 : : {
5239 712 : 775 : rescnt++; /* return last_value if not is_called */
9494 vadim4o@yahoo.com 713 : 775 : 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 : : */
5239 tgl@sss.pgh.pa.us 726 [ + + + + ]: 147732 : if (log < fetch || !seq->is_called)
727 : : {
728 : : /* forced log to satisfy local demand for values */
9024 729 : 2735 : fetch = log = fetch + SEQ_LOG_VALS;
9494 vadim4o@yahoo.com 730 : 2735 : logit = true;
731 : : }
732 : : else
733 : : {
9024 tgl@sss.pgh.pa.us 734 : 144997 : XLogRecPtr redoptr = GetRedoRecPtr();
735 : :
5083 alvherre@alvh.no-ip. 736 [ + + ]: 144997 : if (PageGetLSN(page) <= redoptr)
737 : : {
738 : : /* last update of seq was before checkpoint */
9024 tgl@sss.pgh.pa.us 739 : 82011 : fetch = log = fetch + SEQ_LOG_VALS;
740 : 82011 : logit = true;
741 : : }
742 : : }
743 : :
9382 bruce@momjian.us 744 [ + + ]: 3005531 : while (fetch) /* try to fetch cache [+ log ] numbers */
745 : : {
746 : : /*
747 : : * Check MAXVALUE for ascending sequences and MINVALUE for descending
748 : : * sequences
749 : : */
9666 tgl@sss.pgh.pa.us 750 [ + + ]: 2857836 : if (incby > 0)
751 : : {
752 : : /* ascending sequence */
10674 bruce@momjian.us 753 [ + - + + : 2857483 : if ((maxv >= 0 && next > maxv - incby) ||
- + ]
10674 bruce@momjian.us 754 [ # # ]:UIC 0 : (maxv < 0 && next + incby > maxv))
755 : : {
10674 bruce@momjian.us 756 [ + + ]:GIC 25 : if (rescnt > 0)
9494 vadim4o@yahoo.com 757 : 15 : break; /* stop fetching */
3630 peter_e@gmx.net 758 [ + + ]: 10 : if (!cycle)
8532 tgl@sss.pgh.pa.us 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)));
10674 bruce@momjian.us 764 : 4 : next = minv;
765 : : }
766 : : else
767 : 2857458 : next += incby;
768 : : }
769 : : else
770 : : {
771 : : /* descending sequence */
772 [ + - + + : 353 : if ((minv < 0 && next < minv - incby) ||
- + ]
10674 bruce@momjian.us 773 [ # # ]:UIC 0 : (minv >= 0 && next + incby < minv))
774 : : {
10674 bruce@momjian.us 775 [ + + ]:GIC 20 : if (rescnt > 0)
9494 vadim4o@yahoo.com 776 : 12 : break; /* stop fetching */
3630 peter_e@gmx.net 777 [ + + ]: 8 : if (!cycle)
8532 tgl@sss.pgh.pa.us 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)));
10674 bruce@momjian.us 783 : 4 : next = maxv;
784 : : }
785 : : else
786 : 333 : next += incby;
787 : : }
9494 vadim4o@yahoo.com 788 : 2857799 : fetch--;
789 [ + + ]: 2857799 : if (rescnt < cache)
790 : : {
791 : 146983 : log--;
792 : 146983 : rescnt++;
793 : 146983 : last = next;
9382 bruce@momjian.us 794 [ + + ]: 146983 : if (rescnt == 1) /* if it's first result - */
795 : 146947 : result = next; /* it's what to return */
796 : : }
797 : : }
798 : :
9024 tgl@sss.pgh.pa.us 799 : 147722 : log -= fetch; /* adjust for any unfetched numbers */
800 [ - + ]: 147722 : Assert(log >= 0);
801 : :
802 : : /* save info in local cache */
1006 michael@paquier.xyz 803 : 147722 : elm->increment = incby;
10674 bruce@momjian.us 804 : 147722 : elm->last = result; /* last returned number */
9494 vadim4o@yahoo.com 805 : 147722 : elm->cached = last; /* last fetched number */
6974 tgl@sss.pgh.pa.us 806 : 147722 : elm->last_valid = true;
807 : :
7844 neilc@samurai.com 808 : 147722 : 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 : : */
4293 andres@anarazel.de 817 [ + + + + : 147722 : if (logit && RelationNeedsWAL(seqrel))
+ + + - +
- ]
818 : 2565 : GetTopTransactionId();
819 : :
820 : : /* ready to change the on-disk (or really, in-buffer) tuple */
9451 tgl@sss.pgh.pa.us 821 : 147722 : 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 : : */
7547 832 : 147722 : MarkBufferDirty(buf);
833 : :
834 : : /* XLOG stuff */
5829 rhaas@postgresql.org 835 [ + + + + : 147722 : 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 : : */
4391 heikki.linnakangas@i 846 : 2565 : XLogBeginInsert();
847 : 2565 : XLogRegisterBuffer(0, buf, REGBUF_WILL_INIT);
848 : :
849 : : /* set values that will be saved in xlog */
9466 vadim4o@yahoo.com 850 : 2565 : seq->last_value = next;
9235 tgl@sss.pgh.pa.us 851 : 2565 : seq->is_called = true;
9466 vadim4o@yahoo.com 852 : 2565 : seq->log_cnt = 0;
853 : :
1606 rhaas@postgresql.org 854 : 2565 : xlrec.locator = seqrel->rd_locator;
855 : :
655 peter@eisentraut.org 856 : 2565 : XLogRegisterData(&xlrec, sizeof(xl_seq_rec));
857 : 2565 : XLogRegisterData(seqdatatuple.t_data, seqdatatuple.t_len);
858 : :
4391 heikki.linnakangas@i 859 : 2565 : recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG);
860 : :
9466 vadim4o@yahoo.com 861 : 2565 : PageSetLSN(page, recptr);
862 : : }
863 : :
864 : : /* Now update sequence tuple to the intended final state */
9494 865 : 147722 : seq->last_value = last; /* last fetched number */
9235 tgl@sss.pgh.pa.us 866 : 147722 : seq->is_called = true;
9494 vadim4o@yahoo.com 867 : 147722 : seq->log_cnt = log; /* how much is logged */
868 : :
9451 tgl@sss.pgh.pa.us 869 [ - + ]: 147722 : END_CRIT_SECTION();
870 : :
7547 871 : 147722 : UnlockReleaseBuffer(buf);
872 : :
1006 michael@paquier.xyz 873 : 147722 : sequence_close(seqrel, NoLock);
874 : :
7727 tgl@sss.pgh.pa.us 875 : 147722 : 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 : :
4420 peter_e@gmx.net 889 [ + + ]: 77 : if (pg_class_aclcheck(elm->relid, GetUserId(),
890 : : ACL_SELECT | ACL_USAGE) != ACLCHECK_OK)
8532 tgl@sss.pgh.pa.us 891 [ + - ]: 4 : ereport(ERROR,
892 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
893 : : errmsg("permission denied for sequence %s",
894 : : RelationGetRelationName(seqrel))));
895 : :
6974 896 [ + + ]: 73 : if (!elm->last_valid)
8532 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 : :
10674 bruce@momjian.us 902 : 69 : result = elm->last;
903 : :
1006 michael@paquier.xyz 904 : 69 : sequence_close(seqrel, NoLock);
905 : :
9235 tgl@sss.pgh.pa.us 906 : 69 : PG_RETURN_INT64(result);
907 : : }
908 : :
909 : : Datum
7844 neilc@samurai.com 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() */
6131 rhaas@postgresql.org 921 [ + + ]: 28 : if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(last_used_seq->relid)))
7844 neilc@samurai.com 922 [ + - ]: 4 : ereport(ERROR,
923 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
924 : : errmsg("lastval is not yet defined in this session")));
925 : :
3490 peter_e@gmx.net 926 : 24 : seqrel = lock_and_open_sequence(last_used_seq);
927 : :
928 : : /* nextval() must have already been called for this sequence */
6974 tgl@sss.pgh.pa.us 929 [ - + ]: 24 : Assert(last_used_seq->last_valid);
930 : :
4420 peter_e@gmx.net 931 [ + + ]: 24 : if (pg_class_aclcheck(last_used_seq->relid, GetUserId(),
932 : : ACL_SELECT | ACL_USAGE) != ACLCHECK_OK)
7844 neilc@samurai.com 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;
1006 michael@paquier.xyz 939 : 20 : sequence_close(seqrel, NoLock);
940 : :
7844 neilc@samurai.com 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
388 akapila@postgresql.o 958 : 370 : 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 */
7727 tgl@sss.pgh.pa.us 971 : 370 : init_sequence(relid, &elm, &seqrel);
972 : :
9018 973 [ + + ]: 370 : if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
8532 974 [ + - ]: 4 : ereport(ERROR,
975 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
976 : : errmsg("permission denied for sequence %s",
977 : : RelationGetRelationName(seqrel))));
978 : :
3630 peter_e@gmx.net 979 : 366 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
980 [ - + ]: 366 : if (!HeapTupleIsValid(pgstuple))
3630 peter_e@gmx.net 981 [ # # ]:UIC 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
3630 peter_e@gmx.net 982 :GIC 366 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
983 : 366 : maxv = pgsform->seqmax;
984 : 366 : minv = pgsform->seqmin;
985 : 366 : ReleaseSysCache(pgstuple);
986 : :
987 : : /* read-only transactions may only modify temp sequences */
5094 tgl@sss.pgh.pa.us 988 [ + + ]: 366 : if (!seqrel->rd_islocaltemp)
6125 989 : 194 : 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 : : */
4230 rhaas@postgresql.org 996 : 362 : PreventCommandIfParallelMode("setval()");
997 : :
998 : : /* lock page buffer and read tuple */
3630 peter_e@gmx.net 999 : 362 : seq = read_seq_tuple(seqrel, &buf, &seqdatatuple);
1000 : :
1001 [ + + + + ]: 362 : if ((next < minv) || (next > maxv))
8532 tgl@sss.pgh.pa.us 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 */
6974 1009 [ + + ]: 354 : 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 : 354 : elm->cached = elm->last;
1017 : :
1018 : : /* check the comment above nextval_internal()'s equivalent call. */
4293 andres@anarazel.de 1019 [ + + + + : 354 : if (RelationNeedsWAL(seqrel))
+ + + - ]
1020 : 166 : GetTopTransactionId();
1021 : :
1022 : : /* ready to change the on-disk (or really, in-buffer) tuple */
9451 tgl@sss.pgh.pa.us 1023 : 354 : START_CRIT_SECTION();
1024 : :
5239 1025 : 354 : seq->last_value = next; /* last fetched number */
1026 : 354 : seq->is_called = iscalled;
1027 : 354 : seq->log_cnt = 0;
1028 : :
7547 1029 : 354 : MarkBufferDirty(buf);
1030 : :
1031 : : /* XLOG stuff */
5829 rhaas@postgresql.org 1032 [ + + + + : 354 : if (RelationNeedsWAL(seqrel))
+ + + - ]
1033 : : {
1034 : : xl_seq_rec xlrec;
1035 : : XLogRecPtr recptr;
3874 kgrittn@postgresql.o 1036 : 166 : Page page = BufferGetPage(buf);
1037 : :
4391 heikki.linnakangas@i 1038 : 166 : XLogBeginInsert();
1039 : 166 : XLogRegisterBuffer(0, buf, REGBUF_WILL_INIT);
1040 : :
1606 rhaas@postgresql.org 1041 : 166 : xlrec.locator = seqrel->rd_locator;
655 peter@eisentraut.org 1042 : 166 : XLogRegisterData(&xlrec, sizeof(xl_seq_rec));
1043 : 166 : XLogRegisterData(seqdatatuple.t_data, seqdatatuple.t_len);
1044 : :
4391 heikki.linnakangas@i 1045 : 166 : recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG);
1046 : :
9466 vadim4o@yahoo.com 1047 : 166 : PageSetLSN(page, recptr);
1048 : : }
1049 : :
9451 tgl@sss.pgh.pa.us 1050 [ - + ]: 354 : END_CRIT_SECTION();
1051 : :
7547 1052 : 354 : UnlockReleaseBuffer(buf);
1053 : :
1006 michael@paquier.xyz 1054 : 354 : sequence_close(seqrel, NoLock);
9544 pjw@rhyme.com.au 1055 : 354 : }
1056 : :
1057 : : /*
1058 : : * Implement the 2 arg setval procedure.
1059 : : * See SetSequence for discussion.
1060 : : */
1061 : : Datum
7727 tgl@sss.pgh.pa.us 1062 : 95 : setval_oid(PG_FUNCTION_ARGS)
1063 : : {
1064 : 95 : Oid relid = PG_GETARG_OID(0);
9235 1065 : 95 : int64 next = PG_GETARG_INT64(1);
1066 : :
388 akapila@postgresql.o 1067 : 95 : SetSequence(relid, next, true);
1068 : :
9235 tgl@sss.pgh.pa.us 1069 : 79 : PG_RETURN_INT64(next);
1070 : : }
1071 : :
1072 : : /*
1073 : : * Implement the 3 arg setval procedure.
1074 : : * See SetSequence for discussion.
1075 : : */
1076 : : Datum
7727 1077 : 247 : setval3_oid(PG_FUNCTION_ARGS)
1078 : : {
1079 : 247 : Oid relid = PG_GETARG_OID(0);
9235 1080 : 247 : int64 next = PG_GETARG_INT64(1);
9544 pjw@rhyme.com.au 1081 : 247 : bool iscalled = PG_GETARG_BOOL(2);
1082 : :
388 akapila@postgresql.o 1083 : 247 : SetSequence(relid, next, iscalled);
1084 : :
9009 tgl@sss.pgh.pa.us 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
3490 peter_e@gmx.net 1098 : 149346 : lock_and_open_sequence(SeqTable seq)
1099 : : {
1000 heikki.linnakangas@i 1100 : 149346 : LocalTransactionId thislxid = MyProc->vxid.lxid;
1101 : :
1102 : : /* Get the lock if not already held in this xact */
7024 tgl@sss.pgh.pa.us 1103 [ + + ]: 149346 : if (seq->lxid != thislxid)
1104 : : {
1105 : : ResourceOwner currentOwner;
1106 : :
7844 neilc@samurai.com 1107 : 3286 : currentOwner = CurrentResourceOwner;
3335 tgl@sss.pgh.pa.us 1108 : 3286 : CurrentResourceOwner = TopTransactionResourceOwner;
1109 : :
1110 : 3286 : LockRelationOid(seq->relid, RowExclusiveLock);
1111 : :
7844 neilc@samurai.com 1112 : 3286 : CurrentResourceOwner = currentOwner;
1113 : :
1114 : : /* Flag that we have a lock in the current xact */
7024 tgl@sss.pgh.pa.us 1115 : 3286 : seq->lxid = thislxid;
1116 : : }
1117 : :
1118 : : /* We now know we have the lock, and can safely open the rel */
1006 michael@paquier.xyz 1119 : 149346 : return sequence_open(seq->relid, NoLock);
1120 : : }
1121 : :
1122 : : /*
1123 : : * Creates the hash table for storing sequence data
1124 : : */
1125 : : static void
4761 heikki.linnakangas@i 1126 : 420 : create_seq_hashtable(void)
1127 : : {
1128 : : HASHCTL ctl;
1129 : :
1130 : 420 : ctl.keysize = sizeof(Oid);
1131 : 420 : ctl.entrysize = sizeof(SeqTableData);
1132 : :
1133 : 420 : seqhashtab = hash_create("Sequence values", 16, &ctl,
1134 : : HASH_ELEM | HASH_BLOBS);
1135 : 420 : }
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
7727 tgl@sss.pgh.pa.us 1142 : 149322 : 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 */
4761 heikki.linnakangas@i 1149 [ + + ]: 149322 : if (seqhashtab == NULL)
1150 : 420 : create_seq_hashtable();
1151 : :
1152 : 149322 : 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 [ + + ]: 149322 : if (!found)
1163 : : {
1164 : : /* relid already filled in */
1606 rhaas@postgresql.org 1165 : 1325 : elm->filenumber = InvalidRelFileNumber;
7024 tgl@sss.pgh.pa.us 1166 : 1325 : elm->lxid = InvalidLocalTransactionId;
6974 1167 : 1325 : elm->last_valid = false;
3630 peter_e@gmx.net 1168 : 1325 : elm->last = elm->cached = 0;
1169 : : }
1170 : :
1171 : : /*
1172 : : * Open the sequence relation.
1173 : : */
3490 1174 : 149322 : 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 : : */
1606 rhaas@postgresql.org 1181 [ + + ]: 149318 : if (seqrel->rd_rel->relfilenode != elm->filenumber)
1182 : : {
1183 : 1417 : elm->filenumber = seqrel->rd_rel->relfilenode;
5855 tgl@sss.pgh.pa.us 1184 : 1417 : elm->cached = elm->last;
1185 : : }
1186 : :
1187 : : /* Return results */
8956 1188 : 149318 : *p_elm = elm;
1189 : 149318 : *p_rel = seqrel;
10832 vadim4o@yahoo.com 1190 : 149318 : }
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
3630 peter_e@gmx.net 1203 : 149873 : 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 : :
8956 tgl@sss.pgh.pa.us 1210 : 149873 : *buf = ReadBuffer(rel, 0);
1211 : 149873 : LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);
1212 : :
3874 kgrittn@postgresql.o 1213 : 149873 : page = BufferGetPage(*buf);
8956 tgl@sss.pgh.pa.us 1214 : 149873 : sm = (sequence_magic *) PageGetSpecialPointer(page);
1215 : :
1216 [ - + ]: 149873 : if (sm->magic != SEQ_MAGIC)
8524 tgl@sss.pgh.pa.us 1217 [ # # ]:UIC 0 : elog(ERROR, "bad magic number in sequence \"%s\": %08X",
1218 : : RelationGetRelationName(rel), sm->magic);
1219 : :
8956 tgl@sss.pgh.pa.us 1220 :GIC 149873 : lp = PageGetItemId(page, FirstOffsetNumber);
7017 1221 [ - + ]: 149873 : Assert(ItemIdIsNormal(lp));
1222 : :
1223 : : /* Note we currently only bother to set these two fields of *seqdatatuple */
3630 peter_e@gmx.net 1224 : 149873 : seqdatatuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1225 : 149873 : 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 [ - + ]: 149873 : Assert(!(seqdatatuple->t_data->t_infomask & HEAP_XMAX_IS_MULTI));
1236 [ - + ]: 149873 : if (HeapTupleHeaderGetRawXmax(seqdatatuple->t_data) != InvalidTransactionId)
1237 : : {
3630 peter_e@gmx.net 1238 :UIC 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;
4912 jdavis@postgresql.or 1241 : 0 : MarkBufferDirtyHint(*buf, true);
1242 : : }
1243 : :
3630 peter_e@gmx.net 1244 :GIC 149873 : seq = (Form_pg_sequence_data) GETSTRUCT(seqdatatuple);
1245 : :
8956 tgl@sss.pgh.pa.us 1246 : 149873 : 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
3523 peter_e@gmx.net 1272 : 2240 : 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 : : {
3578 1281 : 2240 : DefElem *as_type = NULL;
6769 tgl@sss.pgh.pa.us 1282 : 2240 : DefElem *start_value = NULL;
1283 : 2240 : DefElem *restart_value = NULL;
10673 bruce@momjian.us 1284 : 2240 : DefElem *increment_by = NULL;
1285 : 2240 : DefElem *max_value = NULL;
1286 : 2240 : DefElem *min_value = NULL;
1287 : 2240 : DefElem *cache_value = NULL;
8405 tgl@sss.pgh.pa.us 1288 : 2240 : DefElem *is_cycled = NULL;
1289 : : ListCell *option;
3525 peter_e@gmx.net 1290 : 2240 : bool reset_max_value = false;
1291 : 2240 : bool reset_min_value = false;
1292 : :
3456 tgl@sss.pgh.pa.us 1293 : 2240 : *need_seq_rewrite = false;
7404 1294 : 2240 : *owned_by = NIL;
1295 : :
8654 bruce@momjian.us 1296 [ + + + + : 4787 : foreach(option, options)
+ + ]
1297 : : {
10673 1298 : 2547 : DefElem *defel = (DefElem *) lfirst(option);
1299 : :
3578 peter_e@gmx.net 1300 [ + + ]: 2547 : if (strcmp(defel->defname, "as") == 0)
1301 : : {
1302 [ - + ]: 969 : if (as_type)
1962 dean.a.rasheed@gmail 1303 :UIC 0 : errorConflictingDefElem(defel, pstate);
3578 peter_e@gmx.net 1304 :GIC 969 : as_type = defel;
3456 tgl@sss.pgh.pa.us 1305 : 969 : *need_seq_rewrite = true;
1306 : : }
3578 peter_e@gmx.net 1307 [ + + ]: 1578 : else if (strcmp(defel->defname, "increment") == 0)
1308 : : {
8689 bruce@momjian.us 1309 [ - + ]: 165 : if (increment_by)
1962 dean.a.rasheed@gmail 1310 :UIC 0 : errorConflictingDefElem(defel, pstate);
10674 bruce@momjian.us 1311 :GIC 165 : increment_by = defel;
3456 tgl@sss.pgh.pa.us 1312 : 165 : *need_seq_rewrite = true;
1313 : : }
6770 1314 [ + + ]: 1413 : else if (strcmp(defel->defname, "start") == 0)
1315 : : {
6769 1316 [ - + ]: 156 : if (start_value)
1962 dean.a.rasheed@gmail 1317 :UIC 0 : errorConflictingDefElem(defel, pstate);
6769 tgl@sss.pgh.pa.us 1318 :GIC 156 : start_value = defel;
3456 1319 : 156 : *need_seq_rewrite = true;
1320 : : }
6770 1321 [ + + ]: 1257 : else if (strcmp(defel->defname, "restart") == 0)
1322 : : {
6769 1323 [ - + ]: 63 : if (restart_value)
1962 dean.a.rasheed@gmail 1324 :UIC 0 : errorConflictingDefElem(defel, pstate);
6769 tgl@sss.pgh.pa.us 1325 :GIC 63 : restart_value = defel;
3456 1326 : 63 : *need_seq_rewrite = true;
1327 : : }
9165 bruce@momjian.us 1328 [ + + ]: 1194 : else if (strcmp(defel->defname, "maxvalue") == 0)
1329 : : {
8689 1330 [ - + ]: 116 : if (max_value)
1962 dean.a.rasheed@gmail 1331 :UIC 0 : errorConflictingDefElem(defel, pstate);
10674 bruce@momjian.us 1332 :GIC 116 : max_value = defel;
3456 tgl@sss.pgh.pa.us 1333 : 116 : *need_seq_rewrite = true;
1334 : : }
9165 bruce@momjian.us 1335 [ + + ]: 1078 : else if (strcmp(defel->defname, "minvalue") == 0)
1336 : : {
8689 1337 [ - + ]: 116 : if (min_value)
1962 dean.a.rasheed@gmail 1338 :UIC 0 : errorConflictingDefElem(defel, pstate);
10674 bruce@momjian.us 1339 :GIC 116 : min_value = defel;
3456 tgl@sss.pgh.pa.us 1340 : 116 : *need_seq_rewrite = true;
1341 : : }
9165 bruce@momjian.us 1342 [ + + ]: 962 : else if (strcmp(defel->defname, "cache") == 0)
1343 : : {
8689 1344 [ - + ]: 90 : if (cache_value)
1962 dean.a.rasheed@gmail 1345 :UIC 0 : errorConflictingDefElem(defel, pstate);
10674 bruce@momjian.us 1346 :GIC 90 : cache_value = defel;
3456 tgl@sss.pgh.pa.us 1347 : 90 : *need_seq_rewrite = true;
1348 : : }
9165 bruce@momjian.us 1349 [ + + ]: 872 : else if (strcmp(defel->defname, "cycle") == 0)
1350 : : {
8405 tgl@sss.pgh.pa.us 1351 [ - + ]: 31 : if (is_cycled)
1962 dean.a.rasheed@gmail 1352 :UIC 0 : errorConflictingDefElem(defel, pstate);
8405 tgl@sss.pgh.pa.us 1353 :GIC 31 : is_cycled = defel;
3456 1354 : 31 : *need_seq_rewrite = true;
1355 : : }
7404 1356 [ + - ]: 841 : else if (strcmp(defel->defname, "owned_by") == 0)
1357 : : {
1358 [ - + ]: 841 : if (*owned_by)
1962 dean.a.rasheed@gmail 1359 :UIC 0 : errorConflictingDefElem(defel, pstate);
7404 tgl@sss.pgh.pa.us 1360 :GIC 841 : *owned_by = defGetQualifiedName(defel);
1361 : : }
3523 peter_e@gmx.net 1362 [ # # ]:UIC 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
8532 tgl@sss.pgh.pa.us 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 : : */
5239 tgl@sss.pgh.pa.us 1386 [ + + ]:GIC 2240 : if (isInit)
467 michael@paquier.xyz 1387 : 1264 : *reset_state = true;
1388 : :
1389 : : /* AS type */
3578 peter_e@gmx.net 1390 [ + + ]: 2240 : if (as_type != NULL)
1391 : : {
3482 bruce@momjian.us 1392 : 969 : Oid newtypid = typenameTypeId(pstate, defGetTypeName(as_type));
1393 : :
3525 peter_e@gmx.net 1394 [ + + + + ]: 965 : if (newtypid != INT2OID &&
1395 [ + + ]: 93 : newtypid != INT4OID &&
1396 : : newtypid != INT8OID)
3578 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 : :
3525 1403 [ + + ]: 949 : 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) ||
3447 tgl@sss.pgh.pa.us 1413 [ + + + - ]: 24 : (seqform->seqtypid == INT8OID && seqform->seqmax == PG_INT64_MAX))
3525 peter_e@gmx.net 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) ||
3447 tgl@sss.pgh.pa.us 1417 [ + + - + ]: 44 : (seqform->seqtypid == INT8OID && seqform->seqmin == PG_INT64_MIN))
3525 peter_e@gmx.net 1418 : 16 : reset_min_value = true;
1419 : : }
1420 : :
1421 : 949 : seqform->seqtypid = newtypid;
1422 : : }
3578 1423 [ + + ]: 1271 : else if (isInit)
1424 : : {
1425 : 359 : seqform->seqtypid = INT8OID;
1426 : : }
1427 : :
1428 : : /* INCREMENT BY */
8361 neilc@samurai.com 1429 [ + + ]: 2220 : if (increment_by != NULL)
1430 : : {
3630 peter_e@gmx.net 1431 : 165 : seqform->seqincrement = defGetInt64(increment_by);
1432 [ + + ]: 165 : if (seqform->seqincrement == 0)
8532 tgl@sss.pgh.pa.us 1433 [ + - ]: 4 : ereport(ERROR,
1434 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1435 : : errmsg("INCREMENT must not be zero")));
467 michael@paquier.xyz 1436 : 161 : *reset_state = true;
1437 : : }
8405 tgl@sss.pgh.pa.us 1438 [ + + ]: 2055 : else if (isInit)
1439 : : {
3630 peter_e@gmx.net 1440 : 1118 : seqform->seqincrement = 1;
1441 : : }
1442 : :
1443 : : /* CYCLE */
8361 neilc@samurai.com 1444 [ + + ]: 2216 : if (is_cycled != NULL)
1445 : : {
1779 peter@eisentraut.org 1446 : 31 : seqform->seqcycle = boolVal(is_cycled->arg);
3630 peter_e@gmx.net 1447 [ + + - + ]: 31 : Assert(BoolIsValid(seqform->seqcycle));
467 michael@paquier.xyz 1448 : 31 : *reset_state = true;
1449 : : }
8405 tgl@sss.pgh.pa.us 1450 [ + + ]: 2185 : else if (isInit)
1451 : : {
3630 peter_e@gmx.net 1452 : 1234 : seqform->seqcycle = false;
1453 : : }
1454 : :
1455 : : /* MAXVALUE (null arg means NO MAXVALUE) */
8361 neilc@samurai.com 1456 [ + + + + ]: 2216 : if (max_value != NULL && max_value->arg)
1457 : : {
3630 peter_e@gmx.net 1458 : 47 : seqform->seqmax = defGetInt64(max_value);
467 michael@paquier.xyz 1459 : 47 : *reset_state = true;
1460 : : }
3525 peter_e@gmx.net 1461 [ + + + - : 2169 : else if (isInit || max_value != NULL || reset_max_value)
+ + ]
1462 : : {
1463 [ + + + + ]: 1260 : if (seqform->seqincrement > 0 || reset_max_value)
1464 : : {
1465 : : /* ascending seq */
3578 1466 [ + + ]: 1237 : if (seqform->seqtypid == INT2OID)
1467 : 48 : seqform->seqmax = PG_INT16_MAX;
1468 [ + + ]: 1189 : else if (seqform->seqtypid == INT4OID)
1469 : 784 : seqform->seqmax = PG_INT32_MAX;
1470 : : else
1471 : 405 : seqform->seqmax = PG_INT64_MAX;
1472 : : }
1473 : : else
3447 tgl@sss.pgh.pa.us 1474 : 23 : seqform->seqmax = -1; /* descending seq */
467 michael@paquier.xyz 1475 : 1260 : *reset_state = true;
1476 : : }
1477 : :
1478 : : /* Validate maximum value. No need to check INT8 as seqmax is an int64 */
3578 peter_e@gmx.net 1479 [ + + + - : 2216 : if ((seqform->seqtypid == INT2OID && (seqform->seqmax < PG_INT16_MIN || seqform->seqmax > PG_INT16_MAX))
+ + ]
1964 drowley@postgresql.o 1480 [ + + + - : 2208 : || (seqform->seqtypid == INT4OID && (seqform->seqmax < PG_INT32_MIN || seqform->seqmax > PG_INT32_MAX)))
- + ]
3578 peter_e@gmx.net 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) */
8361 neilc@samurai.com 1488 [ + + + + ]: 2208 : if (min_value != NULL && min_value->arg)
1489 : : {
3630 peter_e@gmx.net 1490 : 47 : seqform->seqmin = defGetInt64(min_value);
467 michael@paquier.xyz 1491 : 47 : *reset_state = true;
1492 : : }
3525 peter_e@gmx.net 1493 [ + + + - : 2161 : else if (isInit || min_value != NULL || reset_min_value)
+ + ]
1494 : : {
1495 [ + + + + ]: 1226 : if (seqform->seqincrement < 0 || reset_min_value)
1496 : : {
1497 : : /* descending seq */
3578 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
3482 bruce@momjian.us 1506 : 1186 : seqform->seqmin = 1; /* ascending seq */
467 michael@paquier.xyz 1507 : 1226 : *reset_state = true;
1508 : : }
1509 : :
1510 : : /* Validate minimum value. No need to check INT8 as seqmin is an int64 */
3578 peter_e@gmx.net 1511 [ + + + + : 2208 : if ((seqform->seqtypid == INT2OID && (seqform->seqmin < PG_INT16_MIN || seqform->seqmin > PG_INT16_MAX))
+ - ]
1964 drowley@postgresql.o 1512 [ + + + - : 2200 : || (seqform->seqtypid == INT4OID && (seqform->seqmin < PG_INT32_MIN || seqform->seqmin > PG_INT32_MAX)))
- + ]
3578 peter_e@gmx.net 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 */
3630 1520 [ + + ]: 2200 : if (seqform->seqmin >= seqform->seqmax)
8532 tgl@sss.pgh.pa.us 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 */
6769 1528 [ + + ]: 2192 : if (start_value != NULL)
1529 : : {
3630 peter_e@gmx.net 1530 : 156 : seqform->seqstart = defGetInt64(start_value);
1531 : : }
8405 tgl@sss.pgh.pa.us 1532 [ + + ]: 2036 : else if (isInit)
1533 : : {
3630 peter_e@gmx.net 1534 [ + + ]: 1094 : if (seqform->seqincrement > 0)
3447 tgl@sss.pgh.pa.us 1535 : 1078 : seqform->seqstart = seqform->seqmin; /* ascending seq */
1536 : : else
1537 : 16 : seqform->seqstart = seqform->seqmax; /* descending seq */
1538 : : }
1539 : :
1540 : : /* crosscheck START */
3630 peter_e@gmx.net 1541 [ + + ]: 2192 : if (seqform->seqstart < seqform->seqmin)
6770 tgl@sss.pgh.pa.us 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)));
3630 peter_e@gmx.net 1547 [ + + ]: 2188 : if (seqform->seqstart > seqform->seqmax)
6770 tgl@sss.pgh.pa.us 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] */
6769 1555 [ + + ]: 2184 : if (restart_value != NULL)
1556 : : {
1557 [ + + ]: 63 : if (restart_value->arg != NULL)
467 michael@paquier.xyz 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 : : }
6769 tgl@sss.pgh.pa.us 1564 [ + + ]: 2121 : else if (isInit)
1565 : : {
467 michael@paquier.xyz 1566 : 1220 : *last_value = seqform->seqstart;
1567 : 1220 : *is_called = false;
1568 : : }
1569 : :
1570 : : /* crosscheck RESTART (or current value, if changing MIN/MAX) */
1571 [ + + ]: 2184 : if (*last_value < seqform->seqmin)
8532 tgl@sss.pgh.pa.us 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)));
467 michael@paquier.xyz 1577 [ + + ]: 2180 : if (*last_value > seqform->seqmax)
8532 tgl@sss.pgh.pa.us 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 */
8361 neilc@samurai.com 1585 [ + + ]: 2176 : if (cache_value != NULL)
1586 : : {
3630 peter_e@gmx.net 1587 : 90 : seqform->seqcache = defGetInt64(cache_value);
1588 [ + + ]: 90 : if (seqform->seqcache <= 0)
8405 tgl@sss.pgh.pa.us 1589 [ + - ]: 4 : ereport(ERROR,
1590 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1591 : : errmsg("CACHE (%" PRId64 ") must be greater than zero",
1592 : : seqform->seqcache)));
467 michael@paquier.xyz 1593 : 86 : *reset_state = true;
1594 : : }
8405 tgl@sss.pgh.pa.us 1595 [ + + ]: 2086 : else if (isInit)
1596 : : {
3630 peter_e@gmx.net 1597 : 1131 : seqform->seqcache = 1;
1598 : : }
10832 vadim4o@yahoo.com 1599 : 2172 : }
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
3523 peter_e@gmx.net 1610 : 841 : 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 [ + + ]: 841 : deptype = for_identity ? DEPENDENCY_INTERNAL : DEPENDENCY_AUTO;
1618 : :
7404 tgl@sss.pgh.pa.us 1619 : 841 : nnames = list_length(owned_by);
1620 [ - + ]: 841 : Assert(nnames > 0);
1621 [ + + ]: 841 : 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 */
1599 drowley@postgresql.o 1639 : 833 : relname = list_copy_head(owned_by, nnames - 1);
2253 tgl@sss.pgh.pa.us 1640 : 833 : attrname = strVal(llast(owned_by));
1641 : :
1642 : : /* Open and lock rel to ensure it won't go away meanwhile */
7404 1643 : 833 : rel = makeRangeVarFromNameList(relname);
1644 : 833 : tablerel = relation_openrv(rel, AccessShareLock);
1645 : :
1646 : : /* Must be a regular or foreign table */
4945 1647 [ + + ]: 833 : if (!(tablerel->rd_rel->relkind == RELKIND_RELATION ||
3643 rhaas@postgresql.org 1648 [ + + ]: 34 : tablerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE ||
3523 peter_e@gmx.net 1649 [ + - ]: 29 : tablerel->rd_rel->relkind == RELKIND_VIEW ||
3643 rhaas@postgresql.org 1650 [ + + ]: 29 : tablerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
7404 tgl@sss.pgh.pa.us 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 [ - + ]: 829 : if (seqrel->rd_rel->relowner != tablerel->rd_rel->relowner)
7404 tgl@sss.pgh.pa.us 1659 [ # # ]:UIC 0 : ereport(ERROR,
1660 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1661 : : errmsg("sequence must have same owner as table it is linked to")));
7404 tgl@sss.pgh.pa.us 1662 [ + + ]:GIC 829 : 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 : 825 : attnum = get_attnum(RelationGetRelid(tablerel), attrname);
1669 [ + + ]: 825 : 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 : : */
3523 peter_e@gmx.net 1679 [ + + ]: 825 : if (deptype == DEPENDENCY_AUTO)
1680 : : {
1681 : : Oid tableId;
1682 : : int32 colId;
1683 : :
1684 [ + + ]: 545 : 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 : 821 : deleteDependencyRecordsForClass(RelationRelationId, RelationGetRelid(seqrel),
1698 : : RelationRelationId, deptype);
1699 : :
7404 tgl@sss.pgh.pa.us 1700 [ + - ]: 821 : if (tablerel)
1701 : : {
1702 : : ObjectAddress refobject,
1703 : : depobject;
1704 : :
1705 : 821 : refobject.classId = RelationRelationId;
1706 : 821 : refobject.objectId = RelationGetRelid(tablerel);
1707 : 821 : refobject.objectSubId = attnum;
1708 : 821 : depobject.classId = RelationRelationId;
1709 : 821 : depobject.objectId = RelationGetRelid(seqrel);
1710 : 821 : depobject.objectSubId = 0;
3523 peter_e@gmx.net 1711 : 821 : recordDependencyOn(&depobject, &refobject, deptype);
1712 : : }
1713 : :
1714 : : /* Done, but hold lock until commit */
7404 tgl@sss.pgh.pa.us 1715 [ + - ]: 821 : if (tablerel)
1716 : 821 : relation_close(tablerel, NoLock);
1717 : 821 : }
1718 : :
1719 : :
1720 : : /*
1721 : : * Return sequence parameters in a list of the form created by the parser.
1722 : : */
1723 : : List *
3523 peter_e@gmx.net 1724 : 8 : sequence_options(Oid relid)
1725 : : {
1726 : : HeapTuple pgstuple;
1727 : : Form_pg_sequence pgsform;
1728 : 8 : List *options = NIL;
1729 : :
1227 michael@paquier.xyz 1730 : 8 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
3523 peter_e@gmx.net 1731 [ - + ]: 8 : if (!HeapTupleIsValid(pgstuple))
3523 peter_e@gmx.net 1732 [ # # ]:UIC 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
3523 peter_e@gmx.net 1733 :GIC 8 : pgsform = (Form_pg_sequence) GETSTRUCT(pgstuple);
1734 : :
1735 : : /* Use makeFloat() for 64-bit integers, like gram.y does. */
3188 1736 : 8 : options = lappend(options,
1737 : 8 : makeDefElem("cache", (Node *) makeFloat(psprintf(INT64_FORMAT, pgsform->seqcache)), -1));
1738 : 8 : options = lappend(options,
1779 peter@eisentraut.org 1739 : 8 : makeDefElem("cycle", (Node *) makeBoolean(pgsform->seqcycle), -1));
3188 peter_e@gmx.net 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 : :
3523 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
5809 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)
5809 peter_e@gmx.net 1768 [ # # ]:UIC 0 : ereport(ERROR,
1769 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1770 : : errmsg("permission denied for sequence %s",
1771 : : get_rel_name(relid))));
1772 : :
1438 michael@paquier.xyz 1773 [ - + ]:GIC 4 : if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1438 michael@paquier.xyz 1774 [ # # ]:UIC 0 : elog(ERROR, "return type must be a row type");
1775 : :
5809 peter_e@gmx.net 1776 :GIC 4 : memset(isnull, 0, sizeof(isnull));
1777 : :
1227 michael@paquier.xyz 1778 : 4 : pgstuple = SearchSysCache1(SEQRELID, ObjectIdGetDatum(relid));
3630 peter_e@gmx.net 1779 [ - + ]: 4 : if (!HeapTupleIsValid(pgstuple))
3630 peter_e@gmx.net 1780 [ # # ]:UIC 0 : elog(ERROR, "cache lookup failed for sequence %u", relid);
3630 peter_e@gmx.net 1781 :GIC 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);
3578 1789 : 4 : values[6] = ObjectIdGetDatum(pgsform->seqtypid);
1790 : :
3630 1791 : 4 : ReleaseSysCache(pgstuple);
1792 : :
5809 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
820 michael@paquier.xyz 1805 : 679 : pg_get_sequence_data(PG_FUNCTION_ARGS)
1806 : : {
1807 : : #define PG_GET_SEQUENCE_DATA_COLS 3
850 nathan@postgresql.or 1808 : 679 : Oid relid = PG_GETARG_OID(0);
1809 : : Relation seqrel;
820 michael@paquier.xyz 1810 : 679 : Datum values[PG_GET_SEQUENCE_DATA_COLS] = {0};
1811 : 679 : bool isnull[PG_GET_SEQUENCE_DATA_COLS] = {0};
1812 : : TupleDesc resultTupleDesc;
1813 : : HeapTuple resultHeapTuple;
1814 : : Datum result;
1815 : :
1816 : 679 : resultTupleDesc = CreateTemplateTupleDesc(PG_GET_SEQUENCE_DATA_COLS);
850 nathan@postgresql.or 1817 : 679 : TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "last_value",
1818 : : INT8OID, -1, 0);
820 michael@paquier.xyz 1819 : 679 : TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "is_called",
1820 : : BOOLOID, -1, 0);
418 akapila@postgresql.o 1821 : 679 : TupleDescInitEntry(resultTupleDesc, (AttrNumber) 3, "page_lsn",
1822 : : LSNOID, -1, 0);
257 drowley@postgresql.o 1823 : 679 : TupleDescFinalize(resultTupleDesc);
850 nathan@postgresql.or 1824 : 679 : resultTupleDesc = BlessTupleDesc(resultTupleDesc);
1825 : :
323 1826 : 679 : 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 [ + + + - : 1357 : if (seqrel && seqrel->rd_rel->relkind == RELKIND_SEQUENCE &&
+ + ]
1834 : 678 : pg_class_aclcheck(relid, GetUserId(), ACL_SELECT) == ACLCHECK_OK &&
850 1835 [ - + - - ]: 667 : !RELATION_IS_OTHER_TEMP(seqrel) &&
1836 [ + + + + ]: 667 : (RelationIsPermanent(seqrel) || !RecoveryInProgress()))
1837 : 657 : {
1838 : : Buffer buf;
1839 : : HeapTupleData seqtuple;
1840 : : Form_pg_sequence_data seq;
1841 : : Page page;
1842 : :
1843 : 657 : seq = read_seq_tuple(seqrel, &buf, &seqtuple);
418 akapila@postgresql.o 1844 : 657 : page = BufferGetPage(buf);
1845 : :
850 nathan@postgresql.or 1846 : 657 : values[0] = Int64GetDatum(seq->last_value);
820 michael@paquier.xyz 1847 : 657 : values[1] = BoolGetDatum(seq->is_called);
418 akapila@postgresql.o 1848 : 657 : values[2] = LSNGetDatum(PageGetLSN(page));
1849 : :
850 nathan@postgresql.or 1850 : 657 : UnlockReleaseBuffer(buf);
1851 : : }
1852 : : else
1853 : 22 : memset(isnull, true, sizeof(isnull));
1854 : :
323 1855 [ + + ]: 679 : if (seqrel)
1856 : 678 : relation_close(seqrel, AccessShareLock);
1857 : :
850 1858 : 679 : resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
1859 : 679 : result = HeapTupleGetDatum(resultHeapTuple);
1860 : 679 : 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
3662 peter_e@gmx.net 1871 : 77 : pg_sequence_last_value(PG_FUNCTION_ARGS)
1872 : : {
1873 : 77 : Oid relid = PG_GETARG_OID(0);
1874 : : SeqTable elm;
1875 : : Relation seqrel;
929 nathan@postgresql.or 1876 : 77 : bool is_called = false;
1877 : 77 : int64 result = 0;
1878 : :
1879 : : /* open and lock sequence */
3662 peter_e@gmx.net 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 : : */
880 nathan@postgresql.or 1891 [ + - ]: 77 : if (pg_class_aclcheck(relid, GetUserId(), ACL_SELECT | ACL_USAGE) == ACLCHECK_OK &&
1892 [ - + - - ]: 77 : !RELATION_IS_OTHER_TEMP(seqrel) &&
929 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 : : }
1006 michael@paquier.xyz 1906 : 77 : sequence_close(seqrel, NoLock);
1907 : :
3662 peter_e@gmx.net 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
4804 rhaas@postgresql.org 1918 : 12 : ResetSequenceCaches(void)
1919 : : {
4761 heikki.linnakangas@i 1920 [ + + ]: 12 : if (seqhashtab)
1921 : : {
1922 : 8 : hash_destroy(seqhashtab);
1923 : 8 : seqhashtab = NULL;
1924 : : }
1925 : :
4800 rhaas@postgresql.org 1926 : 12 : last_used_seq = NULL;
4804 1927 : 12 : }
|