sequence.c 40.5 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
11
 *	  src/backend/commands/sequence.c
12
 *
13 14
 *-------------------------------------------------------------------------
 */
15
#include "postgres.h"
16

17
#include "access/heapam.h"
18 19
#include "access/transam.h"
#include "access/xact.h"
20
#include "access/xlogutils.h"
21
#include "catalog/dependency.h"
22
#include "catalog/namespace.h"
23
#include "catalog/pg_type.h"
24
#include "commands/defrem.h"
25
#include "commands/sequence.h"
26
#include "commands/tablecmds.h"
27
#include "funcapi.h"
B
Bruce Momjian 已提交
28
#include "miscadmin.h"
29
#include "nodes/makefuncs.h"
30 31
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
32
#include "storage/proc.h"
33
#include "storage/smgr.h"
34
#include "utils/acl.h"
B
Bruce Momjian 已提交
35
#include "utils/builtins.h"
36
#include "utils/lsyscache.h"
37
#include "utils/resowner.h"
38
#include "utils/syscache.h"
39

40

V
Vadim B. Mikheev 已提交
41
/*
42
 * We don't want to log each fetching of a value from a sequence,
V
Vadim B. Mikheev 已提交
43 44 45
 * so we pre-log a few fetches in advance. In the event of
 * crash we can lose as much as we pre-logged.
 */
B
Bruce Momjian 已提交
46
#define SEQ_LOG_VALS	32
47

48 49 50 51 52
/*
 * The "special area" of a sequence's buffer page looks like this.
 */
#define SEQ_MAGIC	  0x1717

53 54
typedef struct sequence_magic
{
55
	uint32		magic;
56
} sequence_magic;
57

58 59 60 61 62 63
/*
 * We store a SeqTable item for every sequence we have touched in the current
 * session.  This is needed to hold onto nextval/currval state.  (We can't
 * rely on the relcache, since it's only, well, a cache, and may decide to
 * discard entries.)
 *
B
Bruce Momjian 已提交
64
 * XXX We use linear search to find pre-existing SeqTable entries.	This is
65 66 67
 * good when only a small number of sequences are touched in a session, but
 * would suck with many different sequences.  Perhaps use a hashtable someday.
 */
68 69
typedef struct SeqTableData
{
70 71
	struct SeqTableData *next;	/* link to next SeqTable object */
	Oid			relid;			/* pg_class OID of this sequence */
72
	Oid			filenode;		/* last seen relfilenode of this sequence */
73
	LocalTransactionId lxid;	/* xact in which we last did a seq op */
74
	bool		last_valid;		/* do we have a valid "last" value? */
75 76 77 78
	int64		last;			/* value last returned by nextval */
	int64		cached;			/* last value already cached for nextval */
	/* if last != cached, we have not used up all the cached values */
	int64		increment;		/* copy of sequence's increment field */
79
	/* note that increment is zero until we first do read_info() */
80
} SeqTableData;
81 82 83

typedef SeqTableData *SeqTable;

84
static SeqTable seqtab = NULL;	/* Head of list of SeqTable items */
85

86 87 88 89 90
/*
 * last_used_seq is updated by nextval() to point to the last used
 * sequence.
 */
static SeqTableData *last_used_seq = NULL;
91

92
static void fill_seq_with_data(Relation rel, HeapTuple tuple);
93
static int64 nextval_internal(Oid relid);
94
static Relation open_share_lock(SeqTable seq);
95
static void init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel);
96
static Form_pg_sequence read_info(SeqTable elm, Relation rel, Buffer *buf);
97
static void init_params(List *options, bool isInit,
98
			Form_pg_sequence new, List **owned_by);
99
static void do_setval(Oid relid, int64 next, bool iscalled);
100 101
static void process_owned_by(Relation seqrel, List *owned_by);

102 103

/*
B
Bruce Momjian 已提交
104
 * DefineSequence
105
 *				Creates a new sequence relation
106 107
 */
void
108
DefineSequence(CreateSeqStmt *seq)
109
{
110
	FormData_pg_sequence new;
111
	List	   *owned_by;
112
	CreateStmt *stmt = makeNode(CreateStmt);
113
	Oid			seqoid;
114 115 116 117
	Relation	rel;
	HeapTuple	tuple;
	TupleDesc	tupDesc;
	Datum		value[SEQ_COL_LASTCOL];
118
	bool		null[SEQ_COL_LASTCOL];
119
	int			i;
120
	NameData	name;
121

122 123 124 125 126 127
	/* Unlogged sequences are not implemented -- not clear if useful. */
	if (seq->sequence->relpersistence == RELPERSISTENCE_UNLOGGED)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("unlogged sequences are not supported")));

128
	/* Check and set all option values */
129
	init_params(seq->options, true, &new, &owned_by);
130 131

	/*
132
	 * Create relation (and fill value[] and null[] for the tuple)
133 134 135
	 */
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
136
	{
137
		ColumnDef  *coldef = makeNode(ColumnDef);
138

139 140
		coldef->inhcount = 0;
		coldef->is_local = true;
141
		coldef->is_not_null = true;
142
		coldef->storage = 0;
143 144
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
145 146
		coldef->constraints = NIL;

147
		null[i - 1] = false;
148 149 150

		switch (i)
		{
151
			case SEQ_COL_NAME:
P
Peter Eisentraut 已提交
152
				coldef->typeName = makeTypeNameFromOid(NAMEOID, -1, InvalidOid);
153
				coldef->colname = "sequence_name";
154
				namestrcpy(&name, seq->sequence->relname);
155
				value[i - 1] = NameGetDatum(&name);
156 157
				break;
			case SEQ_COL_LASTVAL:
P
Peter Eisentraut 已提交
158
				coldef->typeName = makeTypeNameFromOid(INT8OID, -1, InvalidOid);
159
				coldef->colname = "last_value";
160
				value[i - 1] = Int64GetDatumFast(new.last_value);
161
				break;
162
			case SEQ_COL_STARTVAL:
P
Peter Eisentraut 已提交
163
				coldef->typeName = makeTypeNameFromOid(INT8OID, -1, InvalidOid);
164 165 166
				coldef->colname = "start_value";
				value[i - 1] = Int64GetDatumFast(new.start_value);
				break;
167
			case SEQ_COL_INCBY:
P
Peter Eisentraut 已提交
168
				coldef->typeName = makeTypeNameFromOid(INT8OID, -1, InvalidOid);
169
				coldef->colname = "increment_by";
170
				value[i - 1] = Int64GetDatumFast(new.increment_by);
171 172
				break;
			case SEQ_COL_MAXVALUE:
P
Peter Eisentraut 已提交
173
				coldef->typeName = makeTypeNameFromOid(INT8OID, -1, InvalidOid);
174
				coldef->colname = "max_value";
175
				value[i - 1] = Int64GetDatumFast(new.max_value);
176 177
				break;
			case SEQ_COL_MINVALUE:
P
Peter Eisentraut 已提交
178
				coldef->typeName = makeTypeNameFromOid(INT8OID, -1, InvalidOid);
179
				coldef->colname = "min_value";
180
				value[i - 1] = Int64GetDatumFast(new.min_value);
181 182
				break;
			case SEQ_COL_CACHE:
P
Peter Eisentraut 已提交
183
				coldef->typeName = makeTypeNameFromOid(INT8OID, -1, InvalidOid);
184
				coldef->colname = "cache_value";
185
				value[i - 1] = Int64GetDatumFast(new.cache_value);
186
				break;
V
Vadim B. Mikheev 已提交
187
			case SEQ_COL_LOG:
P
Peter Eisentraut 已提交
188
				coldef->typeName = makeTypeNameFromOid(INT8OID, -1, InvalidOid);
V
Vadim B. Mikheev 已提交
189
				coldef->colname = "log_cnt";
190
				value[i - 1] = Int64GetDatum((int64) 1);
V
Vadim B. Mikheev 已提交
191
				break;
192
			case SEQ_COL_CYCLE:
P
Peter Eisentraut 已提交
193
				coldef->typeName = makeTypeNameFromOid(BOOLOID, -1, InvalidOid);
194
				coldef->colname = "is_cycled";
195
				value[i - 1] = BoolGetDatum(new.is_cycled);
196 197
				break;
			case SEQ_COL_CALLED:
P
Peter Eisentraut 已提交
198
				coldef->typeName = makeTypeNameFromOid(BOOLOID, -1, InvalidOid);
199
				coldef->colname = "is_called";
200
				value[i - 1] = BoolGetDatum(false);
201
				break;
202 203 204 205
		}
		stmt->tableElts = lappend(stmt->tableElts, coldef);
	}

206 207
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
208
	stmt->constraints = NIL;
209
	stmt->options = list_make1(defWithOids(false));
210
	stmt->oncommit = ONCOMMIT_NOOP;
211
	stmt->tablespacename = NULL;
R
Robert Haas 已提交
212
	stmt->if_not_exists = false;
213

214
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE, seq->ownerId);
R
Robert Haas 已提交
215
	Assert(seqoid != InvalidOid);
216

217
	rel = heap_open(seqoid, AccessExclusiveLock);
218
	tupDesc = RelationGetDescr(rel);
219

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
	/* now initialize the sequence's data */
	tuple = heap_form_tuple(tupDesc, value, null);
	fill_seq_with_data(rel, tuple);

	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(rel, owned_by);

	heap_close(rel, NoLock);
}

/*
 * Reset a sequence to its initial value.
 *
 * The change is made transactionally, so that on failure of the current
 * transaction, the sequence will be restored to its previous state.
 * We do that by creating a whole new relfilenode for the sequence; so this
 * works much like the rewriting forms of ALTER TABLE.
 *
 * Caller is assumed to have acquired AccessExclusiveLock on the sequence,
 * which must not be released until end of transaction.  Caller is also
 * responsible for permissions checking.
 */
void
ResetSequence(Oid seq_relid)
{
	Relation	seq_rel;
	SeqTable	elm;
	Form_pg_sequence seq;
	Buffer		buf;
	Page		page;
	HeapTuple	tuple;
	HeapTupleData tupledata;
	ItemId		lp;

	/*
	 * Read the old sequence.  This does a bit more work than really
	 * necessary, but it's simple, and we do want to double-check that it's
	 * indeed a sequence.
	 */
	init_sequence(seq_relid, &elm, &seq_rel);
	seq = read_info(elm, seq_rel, &buf);

	/*
	 * Copy the existing sequence tuple.
	 */
	page = BufferGetPage(buf);
	lp = PageGetItemId(page, FirstOffsetNumber);
	Assert(ItemIdIsNormal(lp));

	tupledata.t_data = (HeapTupleHeader) PageGetItem(page, lp);
	tupledata.t_len = ItemIdGetLength(lp);
	tuple = heap_copytuple(&tupledata);

	/* Now we're done with the old page */
	UnlockReleaseBuffer(buf);

	/*
	 * Modify the copied tuple to execute the restart (compare the RESTART
	 * action in AlterSequence)
	 */
	seq = (Form_pg_sequence) GETSTRUCT(tuple);
	seq->last_value = seq->start_value;
	seq->is_called = false;
	seq->log_cnt = 1;

	/*
	 * Create a new storage file for the sequence.  We want to keep the
	 * sequence's relfrozenxid at 0, since it won't contain any unfrozen XIDs.
	 */
	RelationSetNewRelfilenode(seq_rel, InvalidTransactionId);

	/*
	 * Insert the modified tuple into the new storage file.
	 */
	fill_seq_with_data(seq_rel, tuple);

	/* Clear local cache so that we don't think we have cached numbers */
	/* Note that we do not change the currval() state */
	elm->cached = elm->last;

	relation_close(seq_rel, NoLock);
}

/*
 * Initialize a sequence's relation with the specified tuple as content
 */
static void
fill_seq_with_data(Relation rel, HeapTuple tuple)
{
	Buffer		buf;
	Page		page;
	sequence_magic *sm;

314 315
	/* Initialize first page of relation with special magic number */

316
	buf = ReadBuffer(rel, P_NEW);
317 318
	Assert(BufferGetBlockNumber(buf) == 0);

319
	page = BufferGetPage(buf);
320

321
	PageInit(page, BufferGetPageSize(buf), sizeof(sequence_magic));
322 323 324
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;

325
	/* hack: ensure heap_insert will insert on the just-created page */
326
	RelationSetTargetBlock(rel, 0);
327

328
	/* Now insert sequence tuple */
329
	simple_heap_insert(rel, tuple);
330

331 332
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

333
	/*
334 335
	 * Two special hacks here:
	 *
336 337
	 * 1. Since VACUUM does not process sequences, we have to force the tuple
	 * to have xmin = FrozenTransactionId now.	Otherwise it would become
B
Bruce Momjian 已提交
338
	 * invisible to SELECTs after 2G transactions.	It is okay to do this
339 340 341
	 * because if the current transaction aborts, no other xact will ever
	 * examine the sequence tuple anyway.
	 *
B
Bruce Momjian 已提交
342 343 344 345 346
	 * 2. Even though heap_insert emitted a WAL log record, we have to emit an
	 * XLOG_SEQ_LOG record too, since (a) the heap_insert record will not have
	 * the right xmin, and (b) REDO of the heap_insert record would re-init
	 * page and sequence magic number would be lost.  This means two log
	 * records instead of one :-(
347
	 */
348
	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
349

350
	START_CRIT_SECTION();
351 352 353

	{
		/*
B
Bruce Momjian 已提交
354
		 * Note that the "tuple" structure is still just a local tuple record
355
		 * created by heap_form_tuple; its t_data pointer doesn't point at the
B
Bruce Momjian 已提交
356 357 358
		 * disk buffer.  To scribble on the disk buffer we need to fetch the
		 * item pointer.  But do the same to the local tuple, since that will
		 * be the source for the WAL log record, below.
359 360 361 362 363 364 365
		 */
		ItemId		itemId;
		Item		item;

		itemId = PageGetItemId((Page) page, FirstOffsetNumber);
		item = PageGetItem((Page) page, itemId);

366
		HeapTupleHeaderSetXmin((HeapTupleHeader) item, FrozenTransactionId);
367 368
		((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;

369
		HeapTupleHeaderSetXmin(tuple->t_data, FrozenTransactionId);
370 371 372
		tuple->t_data->t_infomask |= HEAP_XMIN_COMMITTED;
	}

373 374
	MarkBufferDirty(buf);

375
	/* XLOG stuff */
376
	if (RelationNeedsWAL(rel))
377
	{
378 379 380 381
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];
		Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
382 383

		/* We do not log first nextval call, so "advance" sequence here */
384
		/* Note we are scribbling on local tuple, not the disk buffer */
385
		newseq->is_called = true;
386 387 388 389 390
		newseq->log_cnt = 0;

		xlrec.node = rel->rd_node;
		rdata[0].data = (char *) &xlrec;
		rdata[0].len = sizeof(xl_seq_rec);
391
		rdata[0].buffer = InvalidBuffer;
392 393
		rdata[0].next = &(rdata[1]);

394
		rdata[1].data = (char *) tuple->t_data;
395
		rdata[1].len = tuple->t_len;
396
		rdata[1].buffer = InvalidBuffer;
397 398
		rdata[1].next = NULL;

399
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
400 401

		PageSetLSN(page, recptr);
402
		PageSetTLI(page, ThisTimeLineID);
403
	}
404

405
	END_CRIT_SECTION();
406

407
	UnlockReleaseBuffer(buf);
408 409
}

B
Bruce Momjian 已提交
410 411 412
/*
 * AlterSequence
 *
413
 * Modify the definition of a sequence relation
B
Bruce Momjian 已提交
414 415
 */
void
416
AlterSequence(AlterSeqStmt *stmt)
B
Bruce Momjian 已提交
417
{
418
	Oid			relid;
B
Bruce Momjian 已提交
419 420 421 422 423 424
	SeqTable	elm;
	Relation	seqrel;
	Buffer		buf;
	Page		page;
	Form_pg_sequence seq;
	FormData_pg_sequence new;
425
	List	   *owned_by;
B
Bruce Momjian 已提交
426 427

	/* open and AccessShareLock sequence */
428
	relid = RangeVarGetRelid(stmt->sequence, false);
429
	init_sequence(relid, &elm, &seqrel);
B
Bruce Momjian 已提交
430

431 432 433 434 435
	/* allow ALTER to sequence owner only */
	if (!pg_class_ownercheck(relid, GetUserId()))
		aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
					   stmt->sequence->relname);

B
Bruce Momjian 已提交
436
	/* lock page' buffer and read tuple into new sequence structure */
437
	seq = read_info(elm, seqrel, &buf);
B
Bruce Momjian 已提交
438 439
	page = BufferGetPage(buf);

440 441 442 443
	/* Copy old values of options into workspace */
	memcpy(&new, seq, sizeof(FormData_pg_sequence));

	/* Check and set new values */
444
	init_params(stmt->options, false, &new, &owned_by);
B
Bruce Momjian 已提交
445

446 447 448 449
	/* Clear local cache so that we don't think we have cached numbers */
	/* Note that we do not change the currval() state */
	elm->cached = elm->last;

450
	/* Now okay to update the on-disk tuple */
451
	memcpy(seq, &new, sizeof(FormData_pg_sequence));
B
Bruce Momjian 已提交
452 453 454

	START_CRIT_SECTION();

455 456
	MarkBufferDirty(buf);

B
Bruce Momjian 已提交
457
	/* XLOG stuff */
458
	if (RelationNeedsWAL(seqrel))
B
Bruce Momjian 已提交
459 460 461 462 463 464 465 466
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];

		xlrec.node = seqrel->rd_node;
		rdata[0].data = (char *) &xlrec;
		rdata[0].len = sizeof(xl_seq_rec);
467
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
468 469 470 471 472
		rdata[0].next = &(rdata[1]);

		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
473
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
474 475
		rdata[1].next = NULL;

476
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
B
Bruce Momjian 已提交
477 478

		PageSetLSN(page, recptr);
479
		PageSetTLI(page, ThisTimeLineID);
B
Bruce Momjian 已提交
480 481 482 483
	}

	END_CRIT_SECTION();

484
	UnlockReleaseBuffer(buf);
B
Bruce Momjian 已提交
485

486 487 488 489
	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(seqrel, owned_by);

B
Bruce Momjian 已提交
490 491 492
	relation_close(seqrel, NoLock);
}

493

494 495 496 497 498
/*
 * Note: nextval with a text argument is no longer exported as a pg_proc
 * entry, but we keep it around to ease porting of C code that may have
 * called the function directly.
 */
499 500
Datum
nextval(PG_FUNCTION_ARGS)
501
{
502
	text	   *seqin = PG_GETARG_TEXT_P(0);
503
	RangeVar   *sequence;
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
	Oid			relid;

	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin));
	relid = RangeVarGetRelid(sequence, false);

	PG_RETURN_INT64(nextval_internal(relid));
}

Datum
nextval_oid(PG_FUNCTION_ARGS)
{
	Oid			relid = PG_GETARG_OID(0);

	PG_RETURN_INT64(nextval_internal(relid));
}

static int64
nextval_internal(Oid relid)
{
523
	SeqTable	elm;
524
	Relation	seqrel;
525
	Buffer		buf;
526
	Page		page;
527
	Form_pg_sequence seq;
528
	int64		incby,
529 530
				maxv,
				minv,
V
Vadim B. Mikheev 已提交
531 532 533 534
				cache,
				log,
				fetch,
				last;
535
	int64		result,
536 537
				next,
				rescnt = 0;
V
Vadim B. Mikheev 已提交
538
	bool		logit = false;
539

V
Vadim B. Mikheev 已提交
540
	/* open and AccessShareLock sequence */
541
	init_sequence(relid, &elm, &seqrel);
542

543 544
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
545 546
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
547
				 errmsg("permission denied for sequence %s",
548
						RelationGetRelationName(seqrel))));
549

550
	/* read-only transactions may only modify temp sequences */
551
	if (seqrel->rd_backend != MyBackendId)
552 553
		PreventCommandIfReadOnly("nextval()");

554 555
	if (elm->last != elm->cached)		/* some numbers were cached */
	{
556 557
		Assert(elm->last_valid);
		Assert(elm->increment != 0);
558
		elm->last += elm->increment;
559
		relation_close(seqrel, NoLock);
560
		last_used_seq = elm;
561
		return elm->last;
562
	}
563

564
	/* lock page' buffer and read tuple */
565
	seq = read_info(elm, seqrel, &buf);
566
	page = BufferGetPage(buf);
567

V
Vadim B. Mikheev 已提交
568
	last = next = result = seq->last_value;
569 570 571
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
572 573
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
574

575
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
576
	{
577
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
578 579 580
		fetch--;
		log--;
	}
581

582
	/*
B
Bruce Momjian 已提交
583 584 585
	 * Decide whether we should emit a WAL log record.	If so, force up the
	 * fetch count to grab SEQ_LOG_VALS more values than we actually need to
	 * cache.  (These will then be usable without logging.)
586
	 *
587 588 589 590
	 * If this is the first nextval after a checkpoint, we must force a new
	 * WAL record to be written anyway, else replay starting from the
	 * checkpoint would fail to advance the sequence past the logged values.
	 * In this case we may as well fetch extra values.
591
	 */
V
Vadim B. Mikheev 已提交
592 593
	if (log < fetch)
	{
594 595
		/* forced log to satisfy local demand for values */
		fetch = log = fetch + SEQ_LOG_VALS;
V
Vadim B. Mikheev 已提交
596 597
		logit = true;
	}
598 599 600 601 602 603 604 605 606 607 608
	else
	{
		XLogRecPtr	redoptr = GetRedoRecPtr();

		if (XLByteLE(PageGetLSN(page), redoptr))
		{
			/* last update of seq was before checkpoint */
			fetch = log = fetch + SEQ_LOG_VALS;
			logit = true;
		}
	}
V
Vadim B. Mikheev 已提交
609

B
Bruce Momjian 已提交
610
	while (fetch)				/* try to fetch cache [+ log ] numbers */
611
	{
612
		/*
B
Bruce Momjian 已提交
613 614
		 * Check MAXVALUE for ascending sequences and MINVALUE for descending
		 * sequences
615
		 */
616
		if (incby > 0)
617
		{
618
			/* ascending sequence */
619 620 621 622
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
623
					break;		/* stop fetching */
624
				if (!seq->is_cycled)
625
				{
B
Bruce Momjian 已提交
626 627
					char		buf[100];

628
					snprintf(buf, sizeof(buf), INT64_FORMAT, maxv);
629
					ereport(ERROR,
B
Bruce Momjian 已提交
630 631 632
						  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
						   errmsg("nextval: reached maximum value of sequence \"%s\" (%s)",
								  RelationGetRelationName(seqrel), buf)));
633
				}
634 635 636 637 638 639 640
				next = minv;
			}
			else
				next += incby;
		}
		else
		{
641
			/* descending sequence */
642 643 644 645
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
646
					break;		/* stop fetching */
647
				if (!seq->is_cycled)
648
				{
B
Bruce Momjian 已提交
649 650
					char		buf[100];

651
					snprintf(buf, sizeof(buf), INT64_FORMAT, minv);
652
					ereport(ERROR,
B
Bruce Momjian 已提交
653 654 655
						  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
						   errmsg("nextval: reached minimum value of sequence \"%s\" (%s)",
								  RelationGetRelationName(seqrel), buf)));
656
				}
657 658 659 660 661
				next = maxv;
			}
			else
				next += incby;
		}
V
Vadim B. Mikheev 已提交
662 663 664 665 666 667
		fetch--;
		if (rescnt < cache)
		{
			log--;
			rescnt++;
			last = next;
B
Bruce Momjian 已提交
668 669
			if (rescnt == 1)	/* if it's first result - */
				result = next;	/* it's what to return */
V
Vadim B. Mikheev 已提交
670
		}
671 672
	}

673 674 675
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

676 677
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
678
	elm->cached = last;			/* last fetched number */
679
	elm->last_valid = true;
V
Vadim B. Mikheev 已提交
680

681 682
	last_used_seq = elm;

683
	START_CRIT_SECTION();
684

685 686
	MarkBufferDirty(buf);

687
	/* XLOG stuff */
688
	if (logit && RelationNeedsWAL(seqrel))
V
Vadim B. Mikheev 已提交
689 690 691
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
692
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
693

694
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
695
		rdata[0].data = (char *) &xlrec;
696
		rdata[0].len = sizeof(xl_seq_rec);
697
		rdata[0].buffer = InvalidBuffer;
698 699
		rdata[0].next = &(rdata[1]);

700
		/* set values that will be saved in xlog */
701
		seq->last_value = next;
702
		seq->is_called = true;
703
		seq->log_cnt = 0;
704

B
Bruce Momjian 已提交
705 706 707
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
708
		rdata[1].buffer = InvalidBuffer;
709 710
		rdata[1].next = NULL;

711
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
V
Vadim B. Mikheev 已提交
712

713
		PageSetLSN(page, recptr);
714
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
715
	}
716

717
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
718
	seq->last_value = last;		/* last fetched number */
719
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
720
	seq->log_cnt = log;			/* how much is logged */
721

722
	END_CRIT_SECTION();
723

724
	UnlockReleaseBuffer(buf);
725

726 727
	relation_close(seqrel, NoLock);

728
	return result;
729 730
}

731
Datum
732
currval_oid(PG_FUNCTION_ARGS)
733
{
734 735
	Oid			relid = PG_GETARG_OID(0);
	int64		result;
736
	SeqTable	elm;
737
	Relation	seqrel;
738

V
Vadim B. Mikheev 已提交
739
	/* open and AccessShareLock sequence */
740
	init_sequence(relid, &elm, &seqrel);
741

742 743
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
744 745
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
746
				 errmsg("permission denied for sequence %s",
747
						RelationGetRelationName(seqrel))));
748

749
	if (!elm->last_valid)
750 751
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
752
				 errmsg("currval of sequence \"%s\" is not yet defined in this session",
753
						RelationGetRelationName(seqrel))));
754 755 756

	result = elm->last;

757 758
	relation_close(seqrel, NoLock);

759
	PG_RETURN_INT64(result);
760 761
}

762 763 764 765 766 767 768 769 770 771 772 773
Datum
lastval(PG_FUNCTION_ARGS)
{
	Relation	seqrel;
	int64		result;

	if (last_used_seq == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("lastval is not yet defined in this session")));

	/* Someone may have dropped the sequence since the last nextval() */
774
	if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(last_used_seq->relid)))
775 776 777 778
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("lastval is not yet defined in this session")));

779
	seqrel = open_share_lock(last_used_seq);
780 781

	/* nextval() must have already been called for this sequence */
782
	Assert(last_used_seq->last_valid);
783

784 785
	if (pg_class_aclcheck(last_used_seq->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
		pg_class_aclcheck(last_used_seq->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
786 787 788 789 790 791 792
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for sequence %s",
						RelationGetRelationName(seqrel))));

	result = last_used_seq->last;
	relation_close(seqrel, NoLock);
793

794 795 796
	PG_RETURN_INT64(result);
}

B
Bruce Momjian 已提交
797
/*
798 799 800 801
 * Main internal procedure that handles 2 & 3 arg forms of SETVAL.
 *
 * Note that the 3 arg version (which sets the is_called flag) is
 * only for use in pg_dump, and setting the is_called flag may not
B
Bruce Momjian 已提交
802
 * work if multiple users are attached to the database and referencing
803 804
 * the sequence (unlikely if pg_dump is restoring it).
 *
B
Bruce Momjian 已提交
805
 * It is necessary to have the 3 arg version so that pg_dump can
806 807 808 809
 * restore the state of a sequence exactly during data-only restores -
 * it is the only way to clear the is_called flag in an existing
 * sequence.
 */
B
Bruce Momjian 已提交
810
static void
811
do_setval(Oid relid, int64 next, bool iscalled)
M
 
Marc G. Fournier 已提交
812 813
{
	SeqTable	elm;
814
	Relation	seqrel;
815
	Buffer		buf;
816
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
817

818
	/* open and AccessShareLock sequence */
819
	init_sequence(relid, &elm, &seqrel);
820 821

	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
822 823
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
824
				 errmsg("permission denied for sequence %s",
825
						RelationGetRelationName(seqrel))));
M
 
Marc G. Fournier 已提交
826

827
	/* read-only transactions may only modify temp sequences */
828
	if (seqrel->rd_backend != MyBackendId)
829 830
		PreventCommandIfReadOnly("setval()");

831
	/* lock page' buffer and read tuple */
832
	seq = read_info(elm, seqrel, &buf);
M
 
Marc G. Fournier 已提交
833

834
	if ((next < seq->min_value) || (next > seq->max_value))
835
	{
B
Bruce Momjian 已提交
836 837 838 839
		char		bufv[100],
					bufm[100],
					bufx[100];

840 841 842
		snprintf(bufv, sizeof(bufv), INT64_FORMAT, next);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, seq->min_value);
		snprintf(bufx, sizeof(bufx), INT64_FORMAT, seq->max_value);
843 844
		ereport(ERROR,
				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
845
				 errmsg("setval: value %s is out of bounds for sequence \"%s\" (%s..%s)",
846 847
						bufv, RelationGetRelationName(seqrel),
						bufm, bufx)));
848
	}
M
 
Marc G. Fournier 已提交
849

850 851 852 853 854 855 856 857 858
	/* Set the currval() state only if iscalled = true */
	if (iscalled)
	{
		elm->last = next;		/* last returned number */
		elm->last_valid = true;
	}

	/* In any case, forget any future cached numbers */
	elm->cached = elm->last;
M
 
Marc G. Fournier 已提交
859

860
	START_CRIT_SECTION();
861

862 863
	MarkBufferDirty(buf);

864
	/* XLOG stuff */
865
	if (RelationNeedsWAL(seqrel))
V
Vadim B. Mikheev 已提交
866 867 868
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
869
		XLogRecData rdata[2];
870
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
871

872
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
873
		rdata[0].data = (char *) &xlrec;
874
		rdata[0].len = sizeof(xl_seq_rec);
875
		rdata[0].buffer = InvalidBuffer;
876 877
		rdata[0].next = &(rdata[1]);

878
		/* set values that will be saved in xlog */
879
		seq->last_value = next;
880
		seq->is_called = true;
881
		seq->log_cnt = 0;
882

B
Bruce Momjian 已提交
883 884 885
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
886
		rdata[1].buffer = InvalidBuffer;
887 888
		rdata[1].next = NULL;

889
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
890 891

		PageSetLSN(page, recptr);
892
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
893
	}
894

895 896
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
897
	seq->is_called = iscalled;
898
	seq->log_cnt = (iscalled) ? 0 : 1;
899

900
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
901

902
	UnlockReleaseBuffer(buf);
903 904

	relation_close(seqrel, NoLock);
905 906
}

907 908 909 910
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
911
Datum
912
setval_oid(PG_FUNCTION_ARGS)
913
{
914
	Oid			relid = PG_GETARG_OID(0);
915
	int64		next = PG_GETARG_INT64(1);
916

917
	do_setval(relid, next, true);
918

919
	PG_RETURN_INT64(next);
920 921
}

922 923 924 925
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
926
Datum
927
setval3_oid(PG_FUNCTION_ARGS)
928
{
929
	Oid			relid = PG_GETARG_OID(0);
930
	int64		next = PG_GETARG_INT64(1);
931 932
	bool		iscalled = PG_GETARG_BOOL(2);

933
	do_setval(relid, next, iscalled);
934

935
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
936 937
}

938

939
/*
940 941
 * Open the sequence and acquire AccessShareLock if needed
 *
942
 * If we haven't touched the sequence already in this transaction,
B
Bruce Momjian 已提交
943
 * we need to acquire AccessShareLock.	We arrange for the lock to
944 945 946
 * be owned by the top transaction, so that we don't need to do it
 * more than once per xact.
 */
947 948
static Relation
open_share_lock(SeqTable seq)
949
{
950
	LocalTransactionId thislxid = MyProc->lxid;
951

952
	/* Get the lock if not already held in this xact */
953
	if (seq->lxid != thislxid)
954 955 956 957 958 959 960
	{
		ResourceOwner currentOwner;

		currentOwner = CurrentResourceOwner;
		PG_TRY();
		{
			CurrentResourceOwner = TopTransactionResourceOwner;
961
			LockRelationOid(seq->relid, AccessShareLock);
962 963 964 965 966 967 968 969 970 971
		}
		PG_CATCH();
		{
			/* Ensure CurrentResourceOwner is restored on error */
			CurrentResourceOwner = currentOwner;
			PG_RE_THROW();
		}
		PG_END_TRY();
		CurrentResourceOwner = currentOwner;

972
		/* Flag that we have a lock in the current xact */
973
		seq->lxid = thislxid;
974
	}
975 976 977

	/* We now know we have AccessShareLock, and can safely open the rel */
	return relation_open(seq->relid, NoLock);
978 979
}

980
/*
981
 * Given a relation OID, open and lock the sequence.  p_elm and p_rel are
982 983 984
 * output parameters.
 */
static void
985
init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel)
986
{
B
Bruce Momjian 已提交
987
	SeqTable	elm;
988
	Relation	seqrel;
989

990 991 992 993 994 995 996
	/* Look to see if we already have a seqtable entry for relation */
	for (elm = seqtab; elm != NULL; elm = elm->next)
	{
		if (elm->relid == relid)
			break;
	}

997
	/*
998
	 * Allocate new seqtable entry if we didn't find one.
999
	 *
B
Bruce Momjian 已提交
1000 1001 1002
	 * NOTE: seqtable entries remain in the list for the life of a backend. If
	 * the sequence itself is deleted then the entry becomes wasted memory,
	 * but it's small enough that this should not matter.
B
Bruce Momjian 已提交
1003
	 */
1004
	if (elm == NULL)
1005
	{
1006
		/*
B
Bruce Momjian 已提交
1007 1008
		 * Time to make a new seqtable entry.  These entries live as long as
		 * the backend does, so we use plain malloc for them.
1009 1010
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
1011
		if (elm == NULL)
1012 1013 1014
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
1015
		elm->relid = relid;
1016
		elm->filenode = InvalidOid;
1017
		elm->lxid = InvalidLocalTransactionId;
1018
		elm->last_valid = false;
1019 1020 1021
		elm->last = elm->cached = elm->increment = 0;
		elm->next = seqtab;
		seqtab = elm;
1022 1023
	}

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
	/*
	 * Open the sequence relation.
	 */
	seqrel = open_share_lock(elm);

	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
		ereport(ERROR,
				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
				 errmsg("\"%s\" is not a sequence",
						RelationGetRelationName(seqrel))));
1034

1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
	/*
	 * If the sequence has been transactionally replaced since we last saw it,
	 * discard any cached-but-unissued values.  We do not touch the currval()
	 * state, however.
	 */
	if (seqrel->rd_rel->relfilenode != elm->filenode)
	{
		elm->filenode = seqrel->rd_rel->relfilenode;
		elm->cached = elm->last;
	}

	/* Return results */
1047 1048
	*p_elm = elm;
	*p_rel = seqrel;
1049 1050 1051
}


1052 1053
/* Given an opened relation, lock the page buffer and find the tuple */
static Form_pg_sequence
1054
read_info(SeqTable elm, Relation rel, Buffer *buf)
1055
{
1056
	Page		page;
1057 1058 1059 1060
	ItemId		lp;
	HeapTupleData tuple;
	sequence_magic *sm;
	Form_pg_sequence seq;
1061

1062 1063 1064
	*buf = ReadBuffer(rel, 0);
	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);

1065
	page = BufferGetPage(*buf);
1066 1067 1068
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
1069 1070
		elog(ERROR, "bad magic number in sequence \"%s\": %08X",
			 RelationGetRelationName(rel), sm->magic);
1071 1072

	lp = PageGetItemId(page, FirstOffsetNumber);
1073
	Assert(ItemIdIsNormal(lp));
1074
	tuple.t_data = (HeapTupleHeader) PageGetItem(page, lp);
1075 1076 1077

	seq = (Form_pg_sequence) GETSTRUCT(&tuple);

1078
	/* this is a handy place to update our copy of the increment */
1079 1080 1081
	elm->increment = seq->increment_by;

	return seq;
1082 1083
}

1084 1085
/*
 * init_params: process the options list of CREATE or ALTER SEQUENCE,
1086 1087
 * and store the values into appropriate fields of *new.  Also set
 * *owned_by to any OWNED BY option, or to NIL if there is none.
1088 1089 1090 1091
 *
 * If isInit is true, fill any unspecified options with default values;
 * otherwise, do not change existing options that aren't explicitly overridden.
 */
1092
static void
1093
init_params(List *options, bool isInit,
1094
			Form_pg_sequence new, List **owned_by)
1095
{
1096 1097
	DefElem    *start_value = NULL;
	DefElem    *restart_value = NULL;
1098 1099 1100 1101
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
1102
	DefElem    *is_cycled = NULL;
1103
	ListCell   *option;
1104

1105 1106
	*owned_by = NIL;

B
Bruce Momjian 已提交
1107
	foreach(option, options)
1108
	{
1109
		DefElem    *defel = (DefElem *) lfirst(option);
1110

1111
		if (strcmp(defel->defname, "increment") == 0)
1112 1113
		{
			if (increment_by)
1114 1115 1116
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1117
			increment_by = defel;
1118
		}
1119 1120
		else if (strcmp(defel->defname, "start") == 0)
		{
1121
			if (start_value)
1122 1123 1124
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1125
			start_value = defel;
1126 1127
		}
		else if (strcmp(defel->defname, "restart") == 0)
1128
		{
1129
			if (restart_value)
1130 1131 1132
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1133
			restart_value = defel;
1134
		}
1135
		else if (strcmp(defel->defname, "maxvalue") == 0)
1136 1137
		{
			if (max_value)
1138 1139 1140
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1141
			max_value = defel;
1142
		}
1143
		else if (strcmp(defel->defname, "minvalue") == 0)
1144 1145
		{
			if (min_value)
1146 1147 1148
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1149
			min_value = defel;
1150
		}
1151
		else if (strcmp(defel->defname, "cache") == 0)
1152 1153
		{
			if (cache_value)
1154 1155 1156
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1157
			cache_value = defel;
1158
		}
1159
		else if (strcmp(defel->defname, "cycle") == 0)
1160
		{
1161
			if (is_cycled)
1162 1163 1164
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1165
			is_cycled = defel;
1166
		}
1167 1168 1169 1170 1171 1172 1173 1174
		else if (strcmp(defel->defname, "owned_by") == 0)
		{
			if (*owned_by)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
			*owned_by = defGetQualifiedName(defel);
		}
1175
		else
1176
			elog(ERROR, "option \"%s\" not recognized",
1177 1178 1179
				 defel->defname);
	}

B
Bruce Momjian 已提交
1180
	/* INCREMENT BY */
1181
	if (increment_by != NULL)
B
Bruce Momjian 已提交
1182 1183
	{
		new->increment_by = defGetInt64(increment_by);
1184 1185 1186
		if (new->increment_by == 0)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1187
					 errmsg("INCREMENT must not be zero")));
B
Bruce Momjian 已提交
1188
	}
1189 1190 1191 1192
	else if (isInit)
		new->increment_by = 1;

	/* CYCLE */
1193
	if (is_cycled != NULL)
1194 1195
	{
		new->is_cycled = intVal(is_cycled->arg);
1196
		Assert(BoolIsValid(new->is_cycled));
1197 1198 1199
	}
	else if (isInit)
		new->is_cycled = false;
1200

1201
	/* MAXVALUE (null arg means NO MAXVALUE) */
1202
	if (max_value != NULL && max_value->arg)
1203
		new->max_value = defGetInt64(max_value);
1204
	else if (isInit || max_value != NULL)
1205
	{
1206
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1207
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
1208
		else
B
Bruce Momjian 已提交
1209
			new->max_value = -1;	/* descending seq */
1210
	}
1211

1212
	/* MINVALUE (null arg means NO MINVALUE) */
1213
	if (min_value != NULL && min_value->arg)
1214
		new->min_value = defGetInt64(min_value);
1215
	else if (isInit || min_value != NULL)
1216
	{
1217
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1218
			new->min_value = 1; /* ascending seq */
1219
		else
B
Bruce Momjian 已提交
1220
			new->min_value = SEQ_MINVALUE;		/* descending seq */
1221
	}
1222

1223
	/* crosscheck min/max */
1224
	if (new->min_value >= new->max_value)
1225
	{
B
Bruce Momjian 已提交
1226 1227 1228
		char		bufm[100],
					bufx[100];

1229 1230
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
		snprintf(bufx, sizeof(bufx), INT64_FORMAT, new->max_value);
1231 1232 1233 1234
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("MINVALUE (%s) must be less than MAXVALUE (%s)",
						bufm, bufx)));
1235
	}
1236

1237 1238 1239
	/* START WITH */
	if (start_value != NULL)
		new->start_value = defGetInt64(start_value);
1240
	else if (isInit)
1241
	{
1242
		if (new->increment_by > 0)
1243
			new->start_value = new->min_value;	/* ascending seq */
1244
		else
1245
			new->start_value = new->max_value;	/* descending seq */
1246
	}
1247

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
	/* crosscheck START */
	if (new->start_value < new->min_value)
	{
		char		bufs[100],
					bufm[100];

		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->start_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("START value (%s) cannot be less than MINVALUE (%s)",
						bufs, bufm)));
	}
	if (new->start_value > new->max_value)
	{
		char		bufs[100],
					bufm[100];

		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->start_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
			  errmsg("START value (%s) cannot be greater than MAXVALUE (%s)",
					 bufs, bufm)));
	}

1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
	/* RESTART [WITH] */
	if (restart_value != NULL)
	{
		if (restart_value->arg != NULL)
			new->last_value = defGetInt64(restart_value);
		else
			new->last_value = new->start_value;
		new->is_called = false;
		new->log_cnt = 1;
	}
	else if (isInit)
	{
		new->last_value = new->start_value;
		new->is_called = false;
		new->log_cnt = 1;
	}

	/* crosscheck RESTART (or current value, if changing MIN/MAX) */
1292
	if (new->last_value < new->min_value)
1293
	{
B
Bruce Momjian 已提交
1294 1295 1296
		char		bufs[100],
					bufm[100];

1297 1298
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
1299 1300
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1301 1302
			   errmsg("RESTART value (%s) cannot be less than MINVALUE (%s)",
					  bufs, bufm)));
1303
	}
1304
	if (new->last_value > new->max_value)
1305
	{
B
Bruce Momjian 已提交
1306 1307 1308
		char		bufs[100],
					bufm[100];

1309 1310
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
1311 1312
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1313 1314
			errmsg("RESTART value (%s) cannot be greater than MAXVALUE (%s)",
				   bufs, bufm)));
1315
	}
1316

B
Bruce Momjian 已提交
1317
	/* CACHE */
1318
	if (cache_value != NULL)
1319
	{
1320 1321 1322 1323
		new->cache_value = defGetInt64(cache_value);
		if (new->cache_value <= 0)
		{
			char		buf[100];
B
Bruce Momjian 已提交
1324

1325 1326 1327 1328 1329 1330
			snprintf(buf, sizeof(buf), INT64_FORMAT, new->cache_value);
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("CACHE (%s) must be greater than zero",
							buf)));
		}
1331
	}
1332 1333
	else if (isInit)
		new->cache_value = 1;
1334 1335
}

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
/*
 * Process an OWNED BY option for CREATE/ALTER SEQUENCE
 *
 * Ownership permissions on the sequence are already checked,
 * but if we are establishing a new owned-by dependency, we must
 * enforce that the referenced table has the same owner and namespace
 * as the sequence.
 */
static void
process_owned_by(Relation seqrel, List *owned_by)
{
	int			nnames;
	Relation	tablerel;
	AttrNumber	attnum;

	nnames = list_length(owned_by);
	Assert(nnames > 0);
	if (nnames == 1)
	{
		/* Must be OWNED BY NONE */
		if (strcmp(strVal(linitial(owned_by)), "none") != 0)
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 errmsg("invalid OWNED BY option"),
B
Bruce Momjian 已提交
1360
				errhint("Specify OWNED BY table.column or OWNED BY NONE.")));
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
		tablerel = NULL;
		attnum = 0;
	}
	else
	{
		List	   *relname;
		char	   *attrname;
		RangeVar   *rel;

		/* Separate relname and attr name */
		relname = list_truncate(list_copy(owned_by), nnames - 1);
		attrname = strVal(lfirst(list_tail(owned_by)));

		/* Open and lock rel to ensure it won't go away meanwhile */
		rel = makeRangeVarFromNameList(relname);
		tablerel = relation_openrv(rel, AccessShareLock);

		/* Must be a regular table */
		if (tablerel->rd_rel->relkind != RELKIND_RELATION)
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("referenced relation \"%s\" is not a table",
							RelationGetRelationName(tablerel))));

		/* We insist on same owner and schema */
		if (seqrel->rd_rel->relowner != tablerel->rd_rel->relowner)
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
B
Bruce Momjian 已提交
1389
					 errmsg("sequence must have same owner as table it is linked to")));
1390 1391 1392
		if (RelationGetNamespace(seqrel) != RelationGetNamespace(tablerel))
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
P
Peter Eisentraut 已提交
1393
					 errmsg("sequence must be in same schema as table it is linked to")));
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

		/* Now, fetch the attribute number from the system cache */
		attnum = get_attnum(RelationGetRelid(tablerel), attrname);
		if (attnum == InvalidAttrNumber)
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("column \"%s\" of relation \"%s\" does not exist",
							attrname, RelationGetRelationName(tablerel))));
	}

	/*
B
Bruce Momjian 已提交
1405 1406
	 * OK, we are ready to update pg_depend.  First remove any existing AUTO
	 * dependencies for the sequence, then optionally add a new one.
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
	 */
	markSequenceUnowned(RelationGetRelid(seqrel));

	if (tablerel)
	{
		ObjectAddress refobject,
					depobject;

		refobject.classId = RelationRelationId;
		refobject.objectId = RelationGetRelid(tablerel);
		refobject.objectSubId = attnum;
		depobject.classId = RelationRelationId;
		depobject.objectId = RelationGetRelid(seqrel);
		depobject.objectSubId = 0;
		recordDependencyOn(&depobject, &refobject, DEPENDENCY_AUTO);
	}

	/* Done, but hold lock until commit */
	if (tablerel)
		relation_close(tablerel, NoLock);
}

V
Vadim B. Mikheev 已提交
1429

1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
/*
 * Return sequence parameters, for use by information schema
 */
Datum
pg_sequence_parameters(PG_FUNCTION_ARGS)
{
	Oid			relid = PG_GETARG_OID(0);
	TupleDesc	tupdesc;
	Datum		values[5];
	bool		isnull[5];
	SeqTable	elm;
	Relation	seqrel;
	Buffer		buf;
	Form_pg_sequence seq;

	/* open and AccessShareLock sequence */
	init_sequence(relid, &elm, &seqrel);

	if (pg_class_aclcheck(relid, GetUserId(), ACL_SELECT | ACL_UPDATE | ACL_USAGE) != ACLCHECK_OK)
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for sequence %s",
						RelationGetRelationName(seqrel))));

	tupdesc = CreateTemplateTupleDesc(5, false);
	TupleDescInitEntry(tupdesc, (AttrNumber) 1, "start_value", INT8OID, -1, 0);
	TupleDescInitEntry(tupdesc, (AttrNumber) 2, "minimum_value", INT8OID, -1, 0);
	TupleDescInitEntry(tupdesc, (AttrNumber) 3, "maximum_value", INT8OID, -1, 0);
	TupleDescInitEntry(tupdesc, (AttrNumber) 4, "increment", INT8OID, -1, 0);
	TupleDescInitEntry(tupdesc, (AttrNumber) 5, "cycle_option", BOOLOID, -1, 0);

	BlessTupleDesc(tupdesc);

	memset(isnull, 0, sizeof(isnull));

	seq = read_info(elm, seqrel, &buf);

	values[0] = Int64GetDatum(seq->start_value);
	values[1] = Int64GetDatum(seq->min_value);
	values[2] = Int64GetDatum(seq->max_value);
	values[3] = Int64GetDatum(seq->increment_by);
	values[4] = BoolGetDatum(seq->is_cycled);

	UnlockReleaseBuffer(buf);
	relation_close(seqrel, NoLock);

	return HeapTupleGetDatum(heap_form_tuple(tupdesc, values, isnull));
}


B
Bruce Momjian 已提交
1480 1481
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
1482
{
B
Bruce Momjian 已提交
1483 1484 1485 1486 1487 1488
	uint8		info = record->xl_info & ~XLR_INFO_MASK;
	Buffer		buffer;
	Page		page;
	char	   *item;
	Size		itemsz;
	xl_seq_rec *xlrec = (xl_seq_rec *) XLogRecGetData(record);
1489
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
1490

1491 1492 1493
	/* Backup blocks are not used in seq records */
	Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));

1494
	if (info != XLOG_SEQ_LOG)
1495
		elog(PANIC, "seq_redo: unknown op code %u", info);
V
Vadim B. Mikheev 已提交
1496

1497
	buffer = XLogReadBuffer(xlrec->node, 0, true);
1498
	Assert(BufferIsValid(buffer));
V
Vadim B. Mikheev 已提交
1499 1500
	page = (Page) BufferGetPage(buffer);

1501 1502
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
1503 1504 1505
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
1506

B
Bruce Momjian 已提交
1507
	item = (char *) xlrec + sizeof(xl_seq_rec);
1508 1509
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
1510
	if (PageAddItem(page, (Item) item, itemsz,
1511
					FirstOffsetNumber, false, false) == InvalidOffsetNumber)
1512
		elog(PANIC, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
1513 1514

	PageSetLSN(page, lsn);
1515
	PageSetTLI(page, ThisTimeLineID);
1516 1517
	MarkBufferDirty(buffer);
	UnlockReleaseBuffer(buffer);
V
Vadim B. Mikheev 已提交
1518 1519
}

B
Bruce Momjian 已提交
1520
void
1521
seq_desc(StringInfo buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
1522
{
B
Bruce Momjian 已提交
1523 1524
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
1525 1526

	if (info == XLOG_SEQ_LOG)
1527
		appendStringInfo(buf, "log: ");
V
Vadim B. Mikheev 已提交
1528 1529
	else
	{
1530
		appendStringInfo(buf, "UNKNOWN");
V
Vadim B. Mikheev 已提交
1531 1532 1533
		return;
	}

1534
	appendStringInfo(buf, "rel %u/%u/%u",
B
Bruce Momjian 已提交
1535
			   xlrec->node.spcNode, xlrec->node.dbNode, xlrec->node.relNode);
V
Vadim B. Mikheev 已提交
1536
}