sequence.c 36.3 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5
 *
6
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
11
 *	  $PostgreSQL: pgsql/src/backend/commands/sequence.c,v 1.151 2008/05/16 23:36:04 tgl Exp $
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"
B
Bruce Momjian 已提交
27
#include "miscadmin.h"
28
#include "nodes/makefuncs.h"
29 30
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
31
#include "storage/proc.h"
32
#include "utils/acl.h"
B
Bruce Momjian 已提交
33
#include "utils/builtins.h"
34
#include "utils/lsyscache.h"
35
#include "utils/resowner.h"
36
#include "utils/syscache.h"
37

38

V
Vadim B. Mikheev 已提交
39
/*
40
 * We don't want to log each fetching of a value from a sequence,
V
Vadim B. Mikheev 已提交
41 42 43
 * 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 已提交
44
#define SEQ_LOG_VALS	32
45

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

51 52
typedef struct sequence_magic
{
53
	uint32		magic;
54
} sequence_magic;
55

56 57 58 59 60 61
/*
 * 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 已提交
62
 * XXX We use linear search to find pre-existing SeqTable entries.	This is
63 64 65
 * 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.
 */
66 67
typedef struct SeqTableData
{
68 69
	struct SeqTableData *next;	/* link to next SeqTable object */
	Oid			relid;			/* pg_class OID 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 73 74 75
	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 */
76
	/* note that increment is zero until we first do read_info() */
77
} SeqTableData;
78 79 80

typedef SeqTableData *SeqTable;

81
static SeqTable seqtab = NULL;	/* Head of list of SeqTable items */
82

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

89
static int64 nextval_internal(Oid relid);
90
static Relation open_share_lock(SeqTable seq);
91
static void init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel);
92
static Form_pg_sequence read_info(SeqTable elm, Relation rel, Buffer *buf);
93
static void init_params(List *options, bool isInit,
94
			Form_pg_sequence new, Form_pg_sequence old, List **owned_by);
95
static void do_setval(Oid relid, int64 next, bool iscalled);
96 97
static void process_owned_by(Relation seqrel, List *owned_by);

98 99

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

121
	/* Check and set all option values */
122
	init_params(seq->options, true, &new, NULL, &owned_by);
123 124

	/*
125
	 * Create relation (and fill value[] and null[] for the tuple)
126 127 128
	 */
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
129
	{
130
		ColumnDef  *coldef = makeNode(ColumnDef);
131

132 133
		coldef->inhcount = 0;
		coldef->is_local = true;
134
		coldef->is_not_null = true;
135 136
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
137 138
		coldef->constraints = NIL;

139 140 141 142
		null[i - 1] = ' ';

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

198 199
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
200
	stmt->constraints = NIL;
B
Bruce Momjian 已提交
201
	stmt->options = list_make1(defWithOids(false));
202
	stmt->oncommit = ONCOMMIT_NOOP;
203
	stmt->tablespacename = NULL;
204

205
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
206

207
	rel = heap_open(seqoid, AccessExclusiveLock);
208
	tupDesc = RelationGetDescr(rel);
209

210 211
	/* Initialize first page of relation with special magic number */

212
	buf = ReadBuffer(rel, P_NEW);
213 214
	Assert(BufferGetBlockNumber(buf) == 0);

215 216 217 218 219 220
	page = (PageHeader) BufferGetPage(buf);

	PageInit((Page) page, BufferGetPageSize(buf), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;

221 222 223
	/* hack: ensure heap_insert will insert on the just-created page */
	rel->rd_targblock = 0;

224
	/* Now form & insert sequence tuple */
225
	tuple = heap_formtuple(tupDesc, value, null);
226
	simple_heap_insert(rel, tuple);
227

228 229
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

230
	/*
231 232
	 * Two special hacks here:
	 *
233 234
	 * 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 已提交
235
	 * invisible to SELECTs after 2G transactions.	It is okay to do this
236 237 238
	 * because if the current transaction aborts, no other xact will ever
	 * examine the sequence tuple anyway.
	 *
B
Bruce Momjian 已提交
239 240 241 242 243
	 * 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 :-(
244
	 */
245
	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
246

247
	START_CRIT_SECTION();
248 249 250

	{
		/*
B
Bruce Momjian 已提交
251 252 253 254 255
		 * Note that the "tuple" structure is still just a local tuple record
		 * created by heap_formtuple; its t_data pointer doesn't point at the
		 * 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.
256 257 258 259 260 261 262
		 */
		ItemId		itemId;
		Item		item;

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

263
		HeapTupleHeaderSetXmin((HeapTupleHeader) item, FrozenTransactionId);
264 265
		((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;

266
		HeapTupleHeaderSetXmin(tuple->t_data, FrozenTransactionId);
267 268 269
		tuple->t_data->t_infomask |= HEAP_XMIN_COMMITTED;
	}

270 271
	MarkBufferDirty(buf);

272 273
	/* XLOG stuff */
	if (!rel->rd_istemp)
274
	{
275 276 277 278
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];
		Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
279 280

		/* We do not log first nextval call, so "advance" sequence here */
281
		/* Note we are scribbling on local tuple, not the disk buffer */
282
		newseq->is_called = true;
283 284 285 286 287
		newseq->log_cnt = 0;

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

291
		rdata[1].data = (char *) tuple->t_data;
292
		rdata[1].len = tuple->t_len;
293
		rdata[1].buffer = InvalidBuffer;
294 295
		rdata[1].next = NULL;

296
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
297 298

		PageSetLSN(page, recptr);
299
		PageSetTLI(page, ThisTimeLineID);
300
	}
301

302
	END_CRIT_SECTION();
303

304 305
	UnlockReleaseBuffer(buf);

306 307 308 309
	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(rel, owned_by);

310
	heap_close(rel, NoLock);
311 312
}

B
Bruce Momjian 已提交
313 314 315
/*
 * AlterSequence
 *
316
 * Modify the definition of a sequence relation
B
Bruce Momjian 已提交
317 318
 */
void
319
AlterSequence(AlterSeqStmt *stmt)
B
Bruce Momjian 已提交
320
{
321
	Oid			relid;
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

	/* find sequence */
	relid = RangeVarGetRelid(stmt->sequence, false);

	/* allow ALTER to sequence owner only */
	/* if you change this, see also callers of AlterSequenceInternal! */
	if (!pg_class_ownercheck(relid, GetUserId()))
		aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
					   stmt->sequence->relname);

	/* do the work */
	AlterSequenceInternal(relid, stmt->options);
}

/*
 * AlterSequenceInternal
 *
 * Same as AlterSequence except that the sequence is specified by OID
 * and we assume the caller already checked permissions.
 */
void
AlterSequenceInternal(Oid relid, List *options)
{
B
Bruce Momjian 已提交
345 346 347 348 349 350
	SeqTable	elm;
	Relation	seqrel;
	Buffer		buf;
	Page		page;
	Form_pg_sequence seq;
	FormData_pg_sequence new;
351
	List	   *owned_by;
B
Bruce Momjian 已提交
352 353

	/* open and AccessShareLock sequence */
354
	init_sequence(relid, &elm, &seqrel);
B
Bruce Momjian 已提交
355 356

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

360 361
	/* Fill workspace with appropriate new info */
	init_params(options, false, &new, seq, &owned_by);
B
Bruce Momjian 已提交
362

363 364 365 366
	/* 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;

367
	/* Now okay to update the on-disk tuple */
368
	memcpy(seq, &new, sizeof(FormData_pg_sequence));
B
Bruce Momjian 已提交
369 370 371

	START_CRIT_SECTION();

372 373
	MarkBufferDirty(buf);

B
Bruce Momjian 已提交
374 375 376 377 378 379 380 381 382 383
	/* XLOG stuff */
	if (!seqrel->rd_istemp)
	{
		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);
384
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
385 386 387 388 389
		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;
390
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
391 392
		rdata[1].next = NULL;

393
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
B
Bruce Momjian 已提交
394 395

		PageSetLSN(page, recptr);
396
		PageSetTLI(page, ThisTimeLineID);
B
Bruce Momjian 已提交
397 398 399 400
	}

	END_CRIT_SECTION();

401
	UnlockReleaseBuffer(buf);
B
Bruce Momjian 已提交
402

403 404 405 406
	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(seqrel, owned_by);

B
Bruce Momjian 已提交
407 408 409
	relation_close(seqrel, NoLock);
}

410

411 412 413 414 415
/*
 * 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.
 */
416 417
Datum
nextval(PG_FUNCTION_ARGS)
418
{
419
	text	   *seqin = PG_GETARG_TEXT_P(0);
420
	RangeVar   *sequence;
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
	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)
{
440
	SeqTable	elm;
441
	Relation	seqrel;
442
	Buffer		buf;
443
	Page		page;
444
	Form_pg_sequence seq;
445
	int64		incby,
446 447
				maxv,
				minv,
V
Vadim B. Mikheev 已提交
448 449 450 451
				cache,
				log,
				fetch,
				last;
452
	int64		result,
453 454
				next,
				rescnt = 0;
V
Vadim B. Mikheev 已提交
455
	bool		logit = false;
456

V
Vadim B. Mikheev 已提交
457
	/* open and AccessShareLock sequence */
458
	init_sequence(relid, &elm, &seqrel);
459

460 461
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
462 463
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
464
				 errmsg("permission denied for sequence %s",
465
						RelationGetRelationName(seqrel))));
466 467 468

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
469 470
		Assert(elm->last_valid);
		Assert(elm->increment != 0);
471
		elm->last += elm->increment;
472
		relation_close(seqrel, NoLock);
473
		last_used_seq = elm;
474
		return elm->last;
475
	}
476

477
	/* lock page' buffer and read tuple */
478
	seq = read_info(elm, seqrel, &buf);
479
	page = BufferGetPage(buf);
480

V
Vadim B. Mikheev 已提交
481
	last = next = result = seq->last_value;
482 483 484
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
485 486
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
487

488
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
489
	{
490
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
491 492 493
		fetch--;
		log--;
	}
494

495
	/*
B
Bruce Momjian 已提交
496 497 498
	 * 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.)
499
	 *
500 501 502 503
	 * 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.
504
	 */
V
Vadim B. Mikheev 已提交
505 506
	if (log < fetch)
	{
507 508
		/* forced log to satisfy local demand for values */
		fetch = log = fetch + SEQ_LOG_VALS;
V
Vadim B. Mikheev 已提交
509 510
		logit = true;
	}
511 512 513 514 515 516 517 518 519 520 521
	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 已提交
522

B
Bruce Momjian 已提交
523
	while (fetch)				/* try to fetch cache [+ log ] numbers */
524
	{
525
		/*
B
Bruce Momjian 已提交
526 527
		 * Check MAXVALUE for ascending sequences and MINVALUE for descending
		 * sequences
528
		 */
529
		if (incby > 0)
530
		{
531
			/* ascending sequence */
532 533 534 535
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
536
					break;		/* stop fetching */
537
				if (!seq->is_cycled)
538
				{
B
Bruce Momjian 已提交
539 540
					char		buf[100];

541
					snprintf(buf, sizeof(buf), INT64_FORMAT, maxv);
542
					ereport(ERROR,
B
Bruce Momjian 已提交
543 544 545
						  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
						   errmsg("nextval: reached maximum value of sequence \"%s\" (%s)",
								  RelationGetRelationName(seqrel), buf)));
546
				}
547 548 549 550 551 552 553
				next = minv;
			}
			else
				next += incby;
		}
		else
		{
554
			/* descending sequence */
555 556 557 558
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
559
					break;		/* stop fetching */
560
				if (!seq->is_cycled)
561
				{
B
Bruce Momjian 已提交
562 563
					char		buf[100];

564
					snprintf(buf, sizeof(buf), INT64_FORMAT, minv);
565
					ereport(ERROR,
B
Bruce Momjian 已提交
566 567 568
						  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
						   errmsg("nextval: reached minimum value of sequence \"%s\" (%s)",
								  RelationGetRelationName(seqrel), buf)));
569
				}
570 571 572 573 574
				next = maxv;
			}
			else
				next += incby;
		}
V
Vadim B. Mikheev 已提交
575 576 577 578 579 580
		fetch--;
		if (rescnt < cache)
		{
			log--;
			rescnt++;
			last = next;
B
Bruce Momjian 已提交
581 582
			if (rescnt == 1)	/* if it's first result - */
				result = next;	/* it's what to return */
V
Vadim B. Mikheev 已提交
583
		}
584 585
	}

586 587 588
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

589 590
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
591
	elm->cached = last;			/* last fetched number */
592
	elm->last_valid = true;
V
Vadim B. Mikheev 已提交
593

594 595
	last_used_seq = elm;

596
	START_CRIT_SECTION();
597

598 599
	MarkBufferDirty(buf);

600 601
	/* XLOG stuff */
	if (logit && !seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
602 603 604
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
605
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
606

607
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
608
		rdata[0].data = (char *) &xlrec;
609
		rdata[0].len = sizeof(xl_seq_rec);
610
		rdata[0].buffer = InvalidBuffer;
611 612
		rdata[0].next = &(rdata[1]);

613
		/* set values that will be saved in xlog */
614
		seq->last_value = next;
615
		seq->is_called = true;
616
		seq->log_cnt = 0;
617

B
Bruce Momjian 已提交
618 619 620
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
621
		rdata[1].buffer = InvalidBuffer;
622 623
		rdata[1].next = NULL;

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

626
		PageSetLSN(page, recptr);
627
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
628
	}
629

630
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
631
	seq->last_value = last;		/* last fetched number */
632
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
633
	seq->log_cnt = log;			/* how much is logged */
634

635
	END_CRIT_SECTION();
636

637
	UnlockReleaseBuffer(buf);
638

639 640
	relation_close(seqrel, NoLock);

641
	return result;
642 643
}

644
Datum
645
currval_oid(PG_FUNCTION_ARGS)
646
{
647 648
	Oid			relid = PG_GETARG_OID(0);
	int64		result;
649
	SeqTable	elm;
650
	Relation	seqrel;
651

V
Vadim B. Mikheev 已提交
652
	/* open and AccessShareLock sequence */
653
	init_sequence(relid, &elm, &seqrel);
654

655 656
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
657 658
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
659
				 errmsg("permission denied for sequence %s",
660
						RelationGetRelationName(seqrel))));
661

662
	if (!elm->last_valid)
663 664
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
665
				 errmsg("currval of sequence \"%s\" is not yet defined in this session",
666
						RelationGetRelationName(seqrel))));
667 668 669

	result = elm->last;

670 671
	relation_close(seqrel, NoLock);

672
	PG_RETURN_INT64(result);
673 674
}

675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
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() */
	if (!SearchSysCacheExists(RELOID,
							  ObjectIdGetDatum(last_used_seq->relid),
							  0, 0, 0))
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("lastval is not yet defined in this session")));

694
	seqrel = open_share_lock(last_used_seq);
695 696

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

699 700
	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)
701 702 703 704 705 706 707
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for sequence %s",
						RelationGetRelationName(seqrel))));

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

709 710 711
	PG_RETURN_INT64(result);
}

B
Bruce Momjian 已提交
712
/*
713 714 715 716
 * 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 已提交
717
 * work if multiple users are attached to the database and referencing
718 719
 * the sequence (unlikely if pg_dump is restoring it).
 *
B
Bruce Momjian 已提交
720
 * It is necessary to have the 3 arg version so that pg_dump can
721 722 723 724
 * 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 已提交
725
static void
726
do_setval(Oid relid, int64 next, bool iscalled)
M
 
Marc G. Fournier 已提交
727 728
{
	SeqTable	elm;
729
	Relation	seqrel;
730
	Buffer		buf;
731
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
732

733
	/* open and AccessShareLock sequence */
734
	init_sequence(relid, &elm, &seqrel);
735 736

	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
737 738
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
739
				 errmsg("permission denied for sequence %s",
740
						RelationGetRelationName(seqrel))));
M
 
Marc G. Fournier 已提交
741

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

745
	if ((next < seq->min_value) || (next > seq->max_value))
746
	{
B
Bruce Momjian 已提交
747 748 749 750
		char		bufv[100],
					bufm[100],
					bufx[100];

751 752 753
		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);
754 755
		ereport(ERROR,
				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
756
				 errmsg("setval: value %s is out of bounds for sequence \"%s\" (%s..%s)",
757 758
						bufv, RelationGetRelationName(seqrel),
						bufm, bufx)));
759
	}
M
 
Marc G. Fournier 已提交
760

761 762 763 764 765 766 767 768 769
	/* 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 已提交
770

771
	START_CRIT_SECTION();
772

773 774
	MarkBufferDirty(buf);

775 776
	/* XLOG stuff */
	if (!seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
777 778 779
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
780
		XLogRecData rdata[2];
781
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
782

783
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
784
		rdata[0].data = (char *) &xlrec;
785
		rdata[0].len = sizeof(xl_seq_rec);
786
		rdata[0].buffer = InvalidBuffer;
787 788
		rdata[0].next = &(rdata[1]);

789
		/* set values that will be saved in xlog */
790
		seq->last_value = next;
791
		seq->is_called = true;
792
		seq->log_cnt = 0;
793

B
Bruce Momjian 已提交
794 795 796
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
797
		rdata[1].buffer = InvalidBuffer;
798 799
		rdata[1].next = NULL;

800
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
801 802

		PageSetLSN(page, recptr);
803
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
804
	}
805

806 807
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
808
	seq->is_called = iscalled;
809
	seq->log_cnt = (iscalled) ? 0 : 1;
810

811
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
812

813
	UnlockReleaseBuffer(buf);
814 815

	relation_close(seqrel, NoLock);
816 817
}

818 819 820 821
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
822
Datum
823
setval_oid(PG_FUNCTION_ARGS)
824
{
825
	Oid			relid = PG_GETARG_OID(0);
826
	int64		next = PG_GETARG_INT64(1);
827

828
	do_setval(relid, next, true);
829

830
	PG_RETURN_INT64(next);
831 832
}

833 834 835 836
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
837
Datum
838
setval3_oid(PG_FUNCTION_ARGS)
839
{
840
	Oid			relid = PG_GETARG_OID(0);
841
	int64		next = PG_GETARG_INT64(1);
842 843
	bool		iscalled = PG_GETARG_BOOL(2);

844
	do_setval(relid, next, iscalled);
845

846
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
847 848
}

849

850
/*
851 852
 * Open the sequence and acquire AccessShareLock if needed
 *
853
 * If we haven't touched the sequence already in this transaction,
B
Bruce Momjian 已提交
854
 * we need to acquire AccessShareLock.	We arrange for the lock to
855 856 857
 * be owned by the top transaction, so that we don't need to do it
 * more than once per xact.
 */
858 859
static Relation
open_share_lock(SeqTable seq)
860
{
861
	LocalTransactionId thislxid = MyProc->lxid;
862

863
	/* Get the lock if not already held in this xact */
864
	if (seq->lxid != thislxid)
865 866 867 868 869 870 871
	{
		ResourceOwner currentOwner;

		currentOwner = CurrentResourceOwner;
		PG_TRY();
		{
			CurrentResourceOwner = TopTransactionResourceOwner;
872
			LockRelationOid(seq->relid, AccessShareLock);
873 874 875 876 877 878 879 880 881 882
		}
		PG_CATCH();
		{
			/* Ensure CurrentResourceOwner is restored on error */
			CurrentResourceOwner = currentOwner;
			PG_RE_THROW();
		}
		PG_END_TRY();
		CurrentResourceOwner = currentOwner;

883
		/* Flag that we have a lock in the current xact */
884
		seq->lxid = thislxid;
885
	}
886 887 888

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

891
/*
892
 * Given a relation OID, open and lock the sequence.  p_elm and p_rel are
893 894 895
 * output parameters.
 */
static void
896
init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel)
897
{
B
Bruce Momjian 已提交
898
	SeqTable	elm;
899
	Relation	seqrel;
900

901 902 903 904 905 906 907
	/* 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;
	}

908
	/*
909
	 * Allocate new seqtable entry if we didn't find one.
910
	 *
B
Bruce Momjian 已提交
911 912 913
	 * 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 已提交
914
	 */
915
	if (elm == NULL)
916
	{
917
		/*
B
Bruce Momjian 已提交
918 919
		 * Time to make a new seqtable entry.  These entries live as long as
		 * the backend does, so we use plain malloc for them.
920 921
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
922
		if (elm == NULL)
923 924 925
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
926
		elm->relid = relid;
927
		elm->lxid = InvalidLocalTransactionId;
928
		elm->last_valid = false;
929 930 931
		elm->last = elm->cached = elm->increment = 0;
		elm->next = seqtab;
		seqtab = elm;
932 933
	}

934 935 936 937 938 939 940 941 942 943
	/*
	 * 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))));
944 945 946

	*p_elm = elm;
	*p_rel = seqrel;
947 948 949
}


950 951
/* Given an opened relation, lock the page buffer and find the tuple */
static Form_pg_sequence
952
read_info(SeqTable elm, Relation rel, Buffer *buf)
953
{
954 955 956 957 958
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
	sequence_magic *sm;
	Form_pg_sequence seq;
959

960 961 962 963 964 965 966
	*buf = ReadBuffer(rel, 0);
	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);

	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
967 968
		elog(ERROR, "bad magic number in sequence \"%s\": %08X",
			 RelationGetRelationName(rel), sm->magic);
969 970

	lp = PageGetItemId(page, FirstOffsetNumber);
971
	Assert(ItemIdIsNormal(lp));
972 973 974 975
	tuple.t_data = (HeapTupleHeader) PageGetItem((Page) page, lp);

	seq = (Form_pg_sequence) GETSTRUCT(&tuple);

976
	/* this is a handy place to update our copy of the increment */
977 978 979
	elm->increment = seq->increment_by;

	return seq;
980 981
}

982 983
/*
 * init_params: process the options list of CREATE or ALTER SEQUENCE,
984 985
 * 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.
986 987 988 989
 *
 * If isInit is true, fill any unspecified options with default values;
 * otherwise, do not change existing options that aren't explicitly overridden.
 */
990
static void
991
init_params(List *options, bool isInit,
992
			Form_pg_sequence new, Form_pg_sequence old, List **owned_by)
993
{
994 995 996 997 998
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
999
	DefElem    *is_cycled = NULL;
1000
	ListCell   *option;
1001

1002 1003
	*owned_by = NIL;

1004 1005 1006 1007 1008 1009
	/* Copy old values of options into workspace */
	if (old != NULL)
		memcpy(new, old, sizeof(FormData_pg_sequence));
	else
		memset(new, 0, sizeof(FormData_pg_sequence));

B
Bruce Momjian 已提交
1010
	foreach(option, options)
1011
	{
1012
		DefElem    *defel = (DefElem *) lfirst(option);
1013

1014
		if (strcmp(defel->defname, "increment") == 0)
1015 1016
		{
			if (increment_by)
1017 1018 1019
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1020
			increment_by = defel;
1021
		}
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		else if (strcmp(defel->defname, "start") == 0)
		{
			if (!isInit)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("use RESTART not START in ALTER SEQUENCE")));
			if (last_value)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
			last_value = defel;
		}
		else if (strcmp(defel->defname, "restart") == 0)
1035
		{
1036 1037 1038 1039
			if (isInit)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("use START not RESTART in CREATE SEQUENCE")));
1040
			if (last_value)
1041 1042 1043
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1044
			last_value = defel;
1045
		}
1046
		else if (strcmp(defel->defname, "maxvalue") == 0)
1047 1048
		{
			if (max_value)
1049 1050 1051
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1052
			max_value = defel;
1053
		}
1054
		else if (strcmp(defel->defname, "minvalue") == 0)
1055 1056
		{
			if (min_value)
1057 1058 1059
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1060
			min_value = defel;
1061
		}
1062
		else if (strcmp(defel->defname, "cache") == 0)
1063 1064
		{
			if (cache_value)
1065 1066 1067
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1068
			cache_value = defel;
1069
		}
1070
		else if (strcmp(defel->defname, "cycle") == 0)
1071
		{
1072
			if (is_cycled)
1073 1074 1075
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1076
			is_cycled = defel;
1077
		}
1078 1079 1080 1081 1082 1083 1084 1085
		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);
		}
1086
		else
1087
			elog(ERROR, "option \"%s\" not recognized",
1088 1089 1090
				 defel->defname);
	}

B
Bruce Momjian 已提交
1091
	/* INCREMENT BY */
1092
	if (increment_by != NULL)
B
Bruce Momjian 已提交
1093 1094
	{
		new->increment_by = defGetInt64(increment_by);
1095 1096 1097
		if (new->increment_by == 0)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1098
					 errmsg("INCREMENT must not be zero")));
B
Bruce Momjian 已提交
1099
	}
1100 1101 1102 1103
	else if (isInit)
		new->increment_by = 1;

	/* CYCLE */
1104
	if (is_cycled != NULL)
1105 1106 1107 1108 1109 1110
	{
		new->is_cycled = intVal(is_cycled->arg);
		Assert(new->is_cycled == false || new->is_cycled == true);
	}
	else if (isInit)
		new->is_cycled = false;
1111

1112
	/* MAXVALUE (null arg means NO MAXVALUE) */
1113
	if (max_value != NULL && max_value->arg)
1114
		new->max_value = defGetInt64(max_value);
1115
	else if (isInit || max_value != NULL)
1116
	{
1117
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1118
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
1119
		else
B
Bruce Momjian 已提交
1120
			new->max_value = -1;	/* descending seq */
1121
	}
1122

1123
	/* MINVALUE (null arg means NO MINVALUE) */
1124
	if (min_value != NULL && min_value->arg)
1125
		new->min_value = defGetInt64(min_value);
1126
	else if (isInit || min_value != NULL)
1127
	{
1128
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1129
			new->min_value = 1; /* ascending seq */
1130
		else
B
Bruce Momjian 已提交
1131
			new->min_value = SEQ_MINVALUE;		/* descending seq */
1132
	}
1133

1134
	/* crosscheck min/max */
1135
	if (new->min_value >= new->max_value)
1136
	{
B
Bruce Momjian 已提交
1137 1138 1139
		char		bufm[100],
					bufx[100];

1140 1141
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
		snprintf(bufx, sizeof(bufx), INT64_FORMAT, new->max_value);
1142 1143 1144 1145
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("MINVALUE (%s) must be less than MAXVALUE (%s)",
						bufm, bufx)));
1146
	}
1147

1148
	/* START/RESTART [WITH] */
1149
	if (last_value != NULL)
1150
	{
1151 1152 1153 1154 1155 1156 1157 1158 1159
		if (last_value->arg != NULL)
			new->last_value = defGetInt64(last_value);
		else
		{
			Assert(old != NULL);
			new->last_value = old->start_value;
		}
		if (isInit)
			new->start_value = new->last_value;
1160 1161 1162
		new->is_called = false;
		new->log_cnt = 1;
	}
1163
	else if (isInit)
1164
	{
1165
		if (new->increment_by > 0)
1166
			new->start_value = new->min_value;	/* ascending seq */
1167
		else
1168 1169
			new->start_value = new->max_value;	/* descending seq */
		new->last_value = new->start_value;
1170 1171
		new->is_called = false;
		new->log_cnt = 1;
1172
	}
1173

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
	/* 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)));
	}

	/* must crosscheck RESTART separately */
1201
	if (new->last_value < new->min_value)
1202
	{
B
Bruce Momjian 已提交
1203 1204 1205
		char		bufs[100],
					bufm[100];

1206 1207
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
1208 1209
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1210
				 errmsg("RESTART value (%s) cannot be less than MINVALUE (%s)",
B
Bruce Momjian 已提交
1211
						bufs, bufm)));
1212
	}
1213
	if (new->last_value > new->max_value)
1214
	{
B
Bruce Momjian 已提交
1215 1216 1217
		char		bufs[100],
					bufm[100];

1218 1219
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
1220 1221
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1222
			  errmsg("RESTART value (%s) cannot be greater than MAXVALUE (%s)",
B
Bruce Momjian 已提交
1223
					 bufs, bufm)));
1224
	}
1225

B
Bruce Momjian 已提交
1226
	/* CACHE */
1227
	if (cache_value != NULL)
1228
	{
1229 1230 1231 1232
		new->cache_value = defGetInt64(cache_value);
		if (new->cache_value <= 0)
		{
			char		buf[100];
B
Bruce Momjian 已提交
1233

1234 1235 1236 1237 1238 1239
			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)));
		}
1240
	}
1241 1242
	else if (isInit)
		new->cache_value = 1;
1243 1244
}

1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
/*
 * 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 已提交
1269
				errhint("Specify OWNED BY table.column or OWNED BY NONE.")));
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
		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 已提交
1298
					 errmsg("sequence must have same owner as table it is linked to")));
1299 1300 1301
		if (RelationGetNamespace(seqrel) != RelationGetNamespace(tablerel))
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
P
Peter Eisentraut 已提交
1302
					 errmsg("sequence must be in same schema as table it is linked to")));
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313

		/* 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 已提交
1314 1315
	 * OK, we are ready to update pg_depend.  First remove any existing AUTO
	 * dependencies for the sequence, then optionally add a new one.
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
	 */
	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 已提交
1338

B
Bruce Momjian 已提交
1339 1340
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
1341
{
B
Bruce Momjian 已提交
1342 1343 1344 1345 1346 1347 1348
	uint8		info = record->xl_info & ~XLR_INFO_MASK;
	Relation	reln;
	Buffer		buffer;
	Page		page;
	char	   *item;
	Size		itemsz;
	xl_seq_rec *xlrec = (xl_seq_rec *) XLogRecGetData(record);
1349
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
1350

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

1354
	reln = XLogOpenRelation(xlrec->node);
1355 1356
	buffer = XLogReadBuffer(reln, 0, true);
	Assert(BufferIsValid(buffer));
V
Vadim B. Mikheev 已提交
1357 1358
	page = (Page) BufferGetPage(buffer);

1359 1360
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
1361 1362 1363
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
1364

B
Bruce Momjian 已提交
1365
	item = (char *) xlrec + sizeof(xl_seq_rec);
1366 1367
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
1368
	if (PageAddItem(page, (Item) item, itemsz,
1369
					FirstOffsetNumber, false, false) == InvalidOffsetNumber)
1370
		elog(PANIC, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
1371 1372

	PageSetLSN(page, lsn);
1373
	PageSetTLI(page, ThisTimeLineID);
1374 1375
	MarkBufferDirty(buffer);
	UnlockReleaseBuffer(buffer);
V
Vadim B. Mikheev 已提交
1376 1377
}

B
Bruce Momjian 已提交
1378
void
1379
seq_desc(StringInfo buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
1380
{
B
Bruce Momjian 已提交
1381 1382
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
1383 1384

	if (info == XLOG_SEQ_LOG)
1385
		appendStringInfo(buf, "log: ");
V
Vadim B. Mikheev 已提交
1386 1387
	else
	{
1388
		appendStringInfo(buf, "UNKNOWN");
V
Vadim B. Mikheev 已提交
1389 1390 1391
		return;
	}

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