sequence.c 36.2 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5
 *
6
 * Portions Copyright (c) 1996-2010, 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.165 2010/02/09 21:43:30 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 "storage/smgr.h"
33
#include "utils/acl.h"
B
Bruce Momjian 已提交
34
#include "utils/builtins.h"
35
#include "utils/lsyscache.h"
36
#include "utils/resowner.h"
37
#include "utils/syscache.h"
38

39

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

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

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

57 58 59 60 61 62
/*
 * 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 已提交
63
 * XXX We use linear search to find pre-existing SeqTable entries.	This is
64 65 66
 * 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.
 */
67 68
typedef struct SeqTableData
{
69 70
	struct SeqTableData *next;	/* link to next SeqTable object */
	Oid			relid;			/* pg_class OID of this sequence */
71
	LocalTransactionId lxid;	/* xact in which we last did a seq op */
72
	bool		last_valid;		/* do we have a valid "last" value? */
73 74 75 76
	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 */
77
	/* note that increment is zero until we first do read_info() */
78
} SeqTableData;
79 80 81

typedef SeqTableData *SeqTable;

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

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

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

99 100

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

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

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

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

141
		null[i - 1] = false;
142 143 144

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

200 201
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
202
	stmt->constraints = NIL;
203
	stmt->options = list_make1(defWithOids(false));
204
	stmt->oncommit = ONCOMMIT_NOOP;
205
	stmt->tablespacename = NULL;
206

207
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
208

209
	rel = heap_open(seqoid, AccessExclusiveLock);
210
	tupDesc = RelationGetDescr(rel);
211

212 213
	/* Initialize first page of relation with special magic number */

214
	buf = ReadBuffer(rel, P_NEW);
215 216
	Assert(BufferGetBlockNumber(buf) == 0);

217
	page = BufferGetPage(buf);
218

219
	PageInit(page, BufferGetPageSize(buf), sizeof(sequence_magic));
220 221 222
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;

223
	/* hack: ensure heap_insert will insert on the just-created page */
224
	RelationSetTargetBlock(rel, 0);
225

226
	/* Now form & insert sequence tuple */
227
	tuple = heap_form_tuple(tupDesc, value, null);
228
	simple_heap_insert(rel, tuple);
229

230 231
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

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

249
	START_CRIT_SECTION();
250 251 252

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

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

265
		HeapTupleHeaderSetXmin((HeapTupleHeader) item, FrozenTransactionId);
266 267
		((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;

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

272 273
	MarkBufferDirty(buf);

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

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

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

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

298
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
299 300

		PageSetLSN(page, recptr);
301
		PageSetTLI(page, ThisTimeLineID);
302
	}
303

304
	END_CRIT_SECTION();
305

306 307
	UnlockReleaseBuffer(buf);

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

312
	heap_close(rel, NoLock);
313 314
}

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

	/* 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 已提交
347 348 349 350 351 352
	SeqTable	elm;
	Relation	seqrel;
	Buffer		buf;
	Page		page;
	Form_pg_sequence seq;
	FormData_pg_sequence new;
353
	List	   *owned_by;
B
Bruce Momjian 已提交
354 355

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

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

362 363 364 365 366
	/* Copy old values of options into workspace */
	memcpy(&new, seq, sizeof(FormData_pg_sequence));

	/* Check and set new values */
	init_params(options, false, &new, &owned_by);
B
Bruce Momjian 已提交
367

368 369 370 371
	/* 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;

372
	/* Now okay to update the on-disk tuple */
373
	memcpy(seq, &new, sizeof(FormData_pg_sequence));
B
Bruce Momjian 已提交
374 375 376

	START_CRIT_SECTION();

377 378
	MarkBufferDirty(buf);

B
Bruce Momjian 已提交
379 380 381 382 383 384 385 386 387 388
	/* 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);
389
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
390 391 392 393 394
		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;
395
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
396 397
		rdata[1].next = NULL;

398
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
B
Bruce Momjian 已提交
399 400

		PageSetLSN(page, recptr);
401
		PageSetTLI(page, ThisTimeLineID);
B
Bruce Momjian 已提交
402 403 404 405
	}

	END_CRIT_SECTION();

406
	UnlockReleaseBuffer(buf);
B
Bruce Momjian 已提交
407

408 409 410 411
	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(seqrel, owned_by);

B
Bruce Momjian 已提交
412 413 414
	relation_close(seqrel, NoLock);
}

415

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

462 463 464
	/* nextval() writes to database and must be prevented during recovery */
	PreventCommandDuringRecovery();

V
Vadim B. Mikheev 已提交
465
	/* open and AccessShareLock sequence */
466
	init_sequence(relid, &elm, &seqrel);
467

468 469
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
470 471
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
472
				 errmsg("permission denied for sequence %s",
473
						RelationGetRelationName(seqrel))));
474 475 476

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
477 478
		Assert(elm->last_valid);
		Assert(elm->increment != 0);
479
		elm->last += elm->increment;
480
		relation_close(seqrel, NoLock);
481
		last_used_seq = elm;
482
		return elm->last;
483
	}
484

485
	/* lock page' buffer and read tuple */
486
	seq = read_info(elm, seqrel, &buf);
487
	page = BufferGetPage(buf);
488

V
Vadim B. Mikheev 已提交
489
	last = next = result = seq->last_value;
490 491 492
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
493 494
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
495

496
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
497
	{
498
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
499 500 501
		fetch--;
		log--;
	}
502

503
	/*
B
Bruce Momjian 已提交
504 505 506
	 * 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.)
507
	 *
508 509 510 511
	 * 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.
512
	 */
V
Vadim B. Mikheev 已提交
513 514
	if (log < fetch)
	{
515 516
		/* forced log to satisfy local demand for values */
		fetch = log = fetch + SEQ_LOG_VALS;
V
Vadim B. Mikheev 已提交
517 518
		logit = true;
	}
519 520 521 522 523 524 525 526 527 528 529
	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 已提交
530

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

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

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

594 595 596
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

597 598
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
599
	elm->cached = last;			/* last fetched number */
600
	elm->last_valid = true;
V
Vadim B. Mikheev 已提交
601

602 603
	last_used_seq = elm;

604
	START_CRIT_SECTION();
605

606 607
	MarkBufferDirty(buf);

608 609
	/* XLOG stuff */
	if (logit && !seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
610 611 612
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
613
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
614

615
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
616
		rdata[0].data = (char *) &xlrec;
617
		rdata[0].len = sizeof(xl_seq_rec);
618
		rdata[0].buffer = InvalidBuffer;
619 620
		rdata[0].next = &(rdata[1]);

621
		/* set values that will be saved in xlog */
622
		seq->last_value = next;
623
		seq->is_called = true;
624
		seq->log_cnt = 0;
625

B
Bruce Momjian 已提交
626 627 628
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
629
		rdata[1].buffer = InvalidBuffer;
630 631
		rdata[1].next = NULL;

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

634
		PageSetLSN(page, recptr);
635
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
636
	}
637

638
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
639
	seq->last_value = last;		/* last fetched number */
640
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
641
	seq->log_cnt = log;			/* how much is logged */
642

643
	END_CRIT_SECTION();
644

645
	UnlockReleaseBuffer(buf);
646

647 648
	relation_close(seqrel, NoLock);

649
	return result;
650 651
}

652
Datum
653
currval_oid(PG_FUNCTION_ARGS)
654
{
655 656
	Oid			relid = PG_GETARG_OID(0);
	int64		result;
657
	SeqTable	elm;
658
	Relation	seqrel;
659

V
Vadim B. Mikheev 已提交
660
	/* open and AccessShareLock sequence */
661
	init_sequence(relid, &elm, &seqrel);
662

663 664
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
665 666
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
667
				 errmsg("permission denied for sequence %s",
668
						RelationGetRelationName(seqrel))));
669

670
	if (!elm->last_valid)
671 672
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
673
				 errmsg("currval of sequence \"%s\" is not yet defined in this session",
674
						RelationGetRelationName(seqrel))));
675 676 677

	result = elm->last;

678 679
	relation_close(seqrel, NoLock);

680
	PG_RETURN_INT64(result);
681 682
}

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
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")));

702
	seqrel = open_share_lock(last_used_seq);
703 704

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

707 708
	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)
709 710 711 712 713 714 715
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for sequence %s",
						RelationGetRelationName(seqrel))));

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

717 718 719
	PG_RETURN_INT64(result);
}

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

741
	/* open and AccessShareLock sequence */
742
	init_sequence(relid, &elm, &seqrel);
743 744

	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
745 746
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
747
				 errmsg("permission denied for sequence %s",
748
						RelationGetRelationName(seqrel))));
M
 
Marc G. Fournier 已提交
749

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

753
	if ((next < seq->min_value) || (next > seq->max_value))
754
	{
B
Bruce Momjian 已提交
755 756 757 758
		char		bufv[100],
					bufm[100],
					bufx[100];

759 760 761
		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);
762 763
		ereport(ERROR,
				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
764
				 errmsg("setval: value %s is out of bounds for sequence \"%s\" (%s..%s)",
765 766
						bufv, RelationGetRelationName(seqrel),
						bufm, bufx)));
767
	}
M
 
Marc G. Fournier 已提交
768

769 770 771 772 773 774 775 776 777
	/* 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 已提交
778

779
	START_CRIT_SECTION();
780

781 782
	MarkBufferDirty(buf);

783 784
	/* XLOG stuff */
	if (!seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
785 786 787
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
788
		XLogRecData rdata[2];
789
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
790

791
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
792
		rdata[0].data = (char *) &xlrec;
793
		rdata[0].len = sizeof(xl_seq_rec);
794
		rdata[0].buffer = InvalidBuffer;
795 796
		rdata[0].next = &(rdata[1]);

797
		/* set values that will be saved in xlog */
798
		seq->last_value = next;
799
		seq->is_called = true;
800
		seq->log_cnt = 0;
801

B
Bruce Momjian 已提交
802 803 804
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
805
		rdata[1].buffer = InvalidBuffer;
806 807
		rdata[1].next = NULL;

808
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
809 810

		PageSetLSN(page, recptr);
811
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
812
	}
813

814 815
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
816
	seq->is_called = iscalled;
817
	seq->log_cnt = (iscalled) ? 0 : 1;
818

819
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
820

821
	UnlockReleaseBuffer(buf);
822 823

	relation_close(seqrel, NoLock);
824 825
}

826 827 828 829
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
830
Datum
831
setval_oid(PG_FUNCTION_ARGS)
832
{
833
	Oid			relid = PG_GETARG_OID(0);
834
	int64		next = PG_GETARG_INT64(1);
835

836
	do_setval(relid, next, true);
837

838
	PG_RETURN_INT64(next);
839 840
}

841 842 843 844
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
845
Datum
846
setval3_oid(PG_FUNCTION_ARGS)
847
{
848
	Oid			relid = PG_GETARG_OID(0);
849
	int64		next = PG_GETARG_INT64(1);
850 851
	bool		iscalled = PG_GETARG_BOOL(2);

852
	do_setval(relid, next, iscalled);
853

854
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
855 856
}

857

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

871
	/* Get the lock if not already held in this xact */
872
	if (seq->lxid != thislxid)
873 874 875 876 877 878 879
	{
		ResourceOwner currentOwner;

		currentOwner = CurrentResourceOwner;
		PG_TRY();
		{
			CurrentResourceOwner = TopTransactionResourceOwner;
880
			LockRelationOid(seq->relid, AccessShareLock);
881 882 883 884 885 886 887 888 889 890
		}
		PG_CATCH();
		{
			/* Ensure CurrentResourceOwner is restored on error */
			CurrentResourceOwner = currentOwner;
			PG_RE_THROW();
		}
		PG_END_TRY();
		CurrentResourceOwner = currentOwner;

891
		/* Flag that we have a lock in the current xact */
892
		seq->lxid = thislxid;
893
	}
894 895 896

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

899
/*
900
 * Given a relation OID, open and lock the sequence.  p_elm and p_rel are
901 902 903
 * output parameters.
 */
static void
904
init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel)
905
{
B
Bruce Momjian 已提交
906
	SeqTable	elm;
907
	Relation	seqrel;
908

909 910 911 912 913 914 915
	/* 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;
	}

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

942 943 944 945 946 947 948 949 950 951
	/*
	 * 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))));
952 953 954

	*p_elm = elm;
	*p_rel = seqrel;
955 956 957
}


958 959
/* Given an opened relation, lock the page buffer and find the tuple */
static Form_pg_sequence
960
read_info(SeqTable elm, Relation rel, Buffer *buf)
961
{
962
	Page		page;
963 964 965 966
	ItemId		lp;
	HeapTupleData tuple;
	sequence_magic *sm;
	Form_pg_sequence seq;
967

968 969 970
	*buf = ReadBuffer(rel, 0);
	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);

971
	page = BufferGetPage(*buf);
972 973 974
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
975 976
		elog(ERROR, "bad magic number in sequence \"%s\": %08X",
			 RelationGetRelationName(rel), sm->magic);
977 978

	lp = PageGetItemId(page, FirstOffsetNumber);
979
	Assert(ItemIdIsNormal(lp));
980
	tuple.t_data = (HeapTupleHeader) PageGetItem(page, lp);
981 982 983

	seq = (Form_pg_sequence) GETSTRUCT(&tuple);

984
	/* this is a handy place to update our copy of the increment */
985 986 987
	elm->increment = seq->increment_by;

	return seq;
988 989
}

990 991
/*
 * init_params: process the options list of CREATE or ALTER SEQUENCE,
992 993
 * 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.
994 995 996 997
 *
 * If isInit is true, fill any unspecified options with default values;
 * otherwise, do not change existing options that aren't explicitly overridden.
 */
998
static void
999
init_params(List *options, bool isInit,
1000
			Form_pg_sequence new, List **owned_by)
1001
{
1002 1003
	DefElem    *start_value = NULL;
	DefElem    *restart_value = NULL;
1004 1005 1006 1007
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
1008
	DefElem    *is_cycled = NULL;
1009
	ListCell   *option;
1010

1011 1012
	*owned_by = NIL;

B
Bruce Momjian 已提交
1013
	foreach(option, options)
1014
	{
1015
		DefElem    *defel = (DefElem *) lfirst(option);
1016

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

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

	/* CYCLE */
1099
	if (is_cycled != NULL)
1100 1101 1102 1103 1104 1105
	{
		new->is_cycled = intVal(is_cycled->arg);
		Assert(new->is_cycled == false || new->is_cycled == true);
	}
	else if (isInit)
		new->is_cycled = false;
1106

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

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

1129
	/* crosscheck min/max */
1130
	if (new->min_value >= new->max_value)
1131
	{
B
Bruce Momjian 已提交
1132 1133 1134
		char		bufm[100],
					bufx[100];

1135 1136
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
		snprintf(bufx, sizeof(bufx), INT64_FORMAT, new->max_value);
1137 1138 1139 1140
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("MINVALUE (%s) must be less than MAXVALUE (%s)",
						bufm, bufx)));
1141
	}
1142

1143 1144 1145
	/* START WITH */
	if (start_value != NULL)
		new->start_value = defGetInt64(start_value);
1146
	else if (isInit)
1147
	{
1148
		if (new->increment_by > 0)
1149
			new->start_value = new->min_value;	/* ascending seq */
1150
		else
1151
			new->start_value = new->max_value;	/* descending seq */
1152
	}
1153

1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
	/* 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)));
	}

1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
	/* 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) */
1198
	if (new->last_value < new->min_value)
1199
	{
B
Bruce Momjian 已提交
1200 1201 1202
		char		bufs[100],
					bufm[100];

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

1215 1216
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
1217 1218
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1219 1220
			errmsg("RESTART value (%s) cannot be greater than MAXVALUE (%s)",
				   bufs, bufm)));
1221
	}
1222

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

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

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
/*
 * 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 已提交
1266
				errhint("Specify OWNED BY table.column or OWNED BY NONE.")));
1267 1268 1269 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
		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 已提交
1295
					 errmsg("sequence must have same owner as table it is linked to")));
1296 1297 1298
		if (RelationGetNamespace(seqrel) != RelationGetNamespace(tablerel))
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
P
Peter Eisentraut 已提交
1299
					 errmsg("sequence must be in same schema as table it is linked to")));
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310

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

B
Bruce Momjian 已提交
1336 1337
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
1338
{
B
Bruce Momjian 已提交
1339 1340 1341 1342 1343 1344
	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);
1345
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
1346

1347 1348 1349
	/* Backup blocks are not used in seq records */
	Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));

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

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

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

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

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

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

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

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