sequence.c 34.0 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5
 *
6
 * Portions Copyright (c) 1996-2007, 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.144 2007/09/05 18:10:47 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 "catalog/dependency.h"
21
#include "catalog/namespace.h"
22
#include "catalog/pg_type.h"
23
#include "commands/defrem.h"
24
#include "commands/sequence.h"
25
#include "commands/tablecmds.h"
B
Bruce Momjian 已提交
26
#include "miscadmin.h"
27
#include "nodes/makefuncs.h"
28
#include "storage/proc.h"
29
#include "utils/acl.h"
B
Bruce Momjian 已提交
30
#include "utils/builtins.h"
31
#include "utils/lsyscache.h"
32
#include "utils/resowner.h"
33
#include "utils/syscache.h"
34

35

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

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

48 49
typedef struct sequence_magic
{
50
	uint32		magic;
51
} sequence_magic;
52

53 54 55 56 57 58
/*
 * 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 已提交
59
 * XXX We use linear search to find pre-existing SeqTable entries.	This is
60 61 62
 * 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.
 */
63 64
typedef struct SeqTableData
{
65 66
	struct SeqTableData *next;	/* link to next SeqTable object */
	Oid			relid;			/* pg_class OID of this sequence */
67
	LocalTransactionId lxid;	/* xact in which we last did a seq op */
68 69 70 71
	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 */
72
} SeqTableData;
73 74 75

typedef SeqTableData *SeqTable;

76
static SeqTable seqtab = NULL;	/* Head of list of SeqTable items */
77

78 79 80 81 82
/*
 * last_used_seq is updated by nextval() to point to the last used
 * sequence.
 */
static SeqTableData *last_used_seq = NULL;
83

84
static int64 nextval_internal(Oid relid);
85
static Relation open_share_lock(SeqTable seq);
86
static void init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel);
87
static Form_pg_sequence read_info(SeqTable elm, Relation rel, Buffer *buf);
88
static void init_params(List *options, bool isInit,
B
Bruce Momjian 已提交
89
			Form_pg_sequence new, List **owned_by);
90
static void do_setval(Oid relid, int64 next, bool iscalled);
91 92
static void process_owned_by(Relation seqrel, List *owned_by);

93 94

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

116
	/* Check and set all option values */
117
	init_params(seq->options, true, &new, &owned_by);
118 119

	/*
120
	 * Create relation (and fill *null & *value)
121 122 123
	 */
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
124
	{
125
		ColumnDef  *coldef = makeNode(ColumnDef);
126

127 128
		coldef->inhcount = 0;
		coldef->is_local = true;
129
		coldef->is_not_null = true;
130 131
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
132 133
		coldef->constraints = NIL;

134 135 136 137
		null[i - 1] = ' ';

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

188 189
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
190
	stmt->constraints = NIL;
B
Bruce Momjian 已提交
191
	stmt->options = list_make1(defWithOids(false));
192
	stmt->oncommit = ONCOMMIT_NOOP;
193
	stmt->tablespacename = NULL;
194

195
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
196

197
	rel = heap_open(seqoid, AccessExclusiveLock);
198
	tupDesc = RelationGetDescr(rel);
199

200 201
	/* Initialize first page of relation with special magic number */

202
	buf = ReadBuffer(rel, P_NEW);
203 204
	Assert(BufferGetBlockNumber(buf) == 0);

205 206 207 208 209 210
	page = (PageHeader) BufferGetPage(buf);

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

211 212 213
	/* hack: ensure heap_insert will insert on the just-created page */
	rel->rd_targblock = 0;

214
	/* Now form & insert sequence tuple */
215
	tuple = heap_formtuple(tupDesc, value, null);
216
	simple_heap_insert(rel, tuple);
217

218 219
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

220
	/*
221 222
	 * Two special hacks here:
	 *
223 224
	 * 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 已提交
225
	 * invisible to SELECTs after 2G transactions.	It is okay to do this
226 227 228
	 * because if the current transaction aborts, no other xact will ever
	 * examine the sequence tuple anyway.
	 *
B
Bruce Momjian 已提交
229 230 231 232 233
	 * 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 :-(
234
	 */
235
	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
236

237
	START_CRIT_SECTION();
238 239 240

	{
		/*
B
Bruce Momjian 已提交
241 242 243 244 245
		 * 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.
246 247 248 249 250 251 252
		 */
		ItemId		itemId;
		Item		item;

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

253
		HeapTupleHeaderSetXmin((HeapTupleHeader) item, FrozenTransactionId);
254 255
		((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;

256
		HeapTupleHeaderSetXmin(tuple->t_data, FrozenTransactionId);
257 258 259
		tuple->t_data->t_infomask |= HEAP_XMIN_COMMITTED;
	}

260 261
	MarkBufferDirty(buf);

262 263
	/* XLOG stuff */
	if (!rel->rd_istemp)
264
	{
265 266 267 268
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];
		Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
269 270

		/* We do not log first nextval call, so "advance" sequence here */
271
		/* Note we are scribbling on local tuple, not the disk buffer */
272
		newseq->is_called = true;
273 274 275 276 277
		newseq->log_cnt = 0;

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

281
		rdata[1].data = (char *) tuple->t_data;
282
		rdata[1].len = tuple->t_len;
283
		rdata[1].buffer = InvalidBuffer;
284 285
		rdata[1].next = NULL;

286
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
287 288

		PageSetLSN(page, recptr);
289
		PageSetTLI(page, ThisTimeLineID);
290
	}
291

292
	END_CRIT_SECTION();
293

294 295
	UnlockReleaseBuffer(buf);

296 297 298 299
	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(rel, owned_by);

300
	heap_close(rel, NoLock);
301 302
}

B
Bruce Momjian 已提交
303 304 305
/*
 * AlterSequence
 *
306
 * Modify the definition of a sequence relation
B
Bruce Momjian 已提交
307 308
 */
void
309
AlterSequence(AlterSeqStmt *stmt)
B
Bruce Momjian 已提交
310
{
311
	Oid			relid;
B
Bruce Momjian 已提交
312 313 314 315 316 317
	SeqTable	elm;
	Relation	seqrel;
	Buffer		buf;
	Page		page;
	Form_pg_sequence seq;
	FormData_pg_sequence new;
318
	List	   *owned_by;
B
Bruce Momjian 已提交
319 320

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

324
	/* allow ALTER to sequence owner only */
B
Bruce Momjian 已提交
325
	if (!pg_class_ownercheck(elm->relid, GetUserId()))
326 327
		aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
					   stmt->sequence->relname);
B
Bruce Momjian 已提交
328 329

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

333 334
	/* Copy old values of options into workspace */
	memcpy(&new, seq, sizeof(FormData_pg_sequence));
B
Bruce Momjian 已提交
335

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

339
	/* Now okay to update the on-disk tuple */
340
	memcpy(seq, &new, sizeof(FormData_pg_sequence));
B
Bruce Momjian 已提交
341

342
	/* Clear local cache so that we don't think we have cached numbers */
B
Bruce Momjian 已提交
343
	elm->last = new.last_value; /* last returned number */
B
Bruce Momjian 已提交
344 345
	elm->cached = new.last_value;		/* last cached number (forget cached
										 * values) */
346

B
Bruce Momjian 已提交
347 348
	START_CRIT_SECTION();

349 350
	MarkBufferDirty(buf);

B
Bruce Momjian 已提交
351 352 353 354 355 356 357 358 359 360
	/* 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);
361
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
362 363 364 365 366
		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;
367
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
368 369
		rdata[1].next = NULL;

370
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
B
Bruce Momjian 已提交
371 372

		PageSetLSN(page, recptr);
373
		PageSetTLI(page, ThisTimeLineID);
B
Bruce Momjian 已提交
374 375 376 377
	}

	END_CRIT_SECTION();

378
	UnlockReleaseBuffer(buf);
B
Bruce Momjian 已提交
379

380 381 382 383
	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(seqrel, owned_by);

B
Bruce Momjian 已提交
384 385 386
	relation_close(seqrel, NoLock);
}

387

388 389 390 391 392
/*
 * 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.
 */
393 394
Datum
nextval(PG_FUNCTION_ARGS)
395
{
396
	text	   *seqin = PG_GETARG_TEXT_P(0);
397
	RangeVar   *sequence;
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
	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)
{
417
	SeqTable	elm;
418
	Relation	seqrel;
419
	Buffer		buf;
420
	Page		page;
421
	Form_pg_sequence seq;
422
	int64		incby,
423 424
				maxv,
				minv,
V
Vadim B. Mikheev 已提交
425 426 427 428
				cache,
				log,
				fetch,
				last;
429
	int64		result,
430 431
				next,
				rescnt = 0;
V
Vadim B. Mikheev 已提交
432
	bool		logit = false;
433

V
Vadim B. Mikheev 已提交
434
	/* open and AccessShareLock sequence */
435
	init_sequence(relid, &elm, &seqrel);
436

437 438
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
439 440
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
441
				 errmsg("permission denied for sequence %s",
442
						RelationGetRelationName(seqrel))));
443 444 445

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
446
		last_used_seq = elm;
447
		elm->last += elm->increment;
448
		relation_close(seqrel, NoLock);
449
		return elm->last;
450
	}
451

452
	/* lock page' buffer and read tuple */
453
	seq = read_info(elm, seqrel, &buf);
454
	page = BufferGetPage(buf);
455

V
Vadim B. Mikheev 已提交
456
	last = next = result = seq->last_value;
457 458 459
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
460 461
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
462

463
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
464
	{
465
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
466 467 468
		fetch--;
		log--;
	}
469

470
	/*
B
Bruce Momjian 已提交
471 472 473
	 * 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.)
474
	 *
475 476 477 478
	 * 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.
479
	 */
V
Vadim B. Mikheev 已提交
480 481
	if (log < fetch)
	{
482 483
		/* forced log to satisfy local demand for values */
		fetch = log = fetch + SEQ_LOG_VALS;
V
Vadim B. Mikheev 已提交
484 485
		logit = true;
	}
486 487 488 489 490 491 492 493 494 495 496
	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 已提交
497

B
Bruce Momjian 已提交
498
	while (fetch)				/* try to fetch cache [+ log ] numbers */
499
	{
500
		/*
B
Bruce Momjian 已提交
501 502
		 * Check MAXVALUE for ascending sequences and MINVALUE for descending
		 * sequences
503
		 */
504
		if (incby > 0)
505
		{
506
			/* ascending sequence */
507 508 509 510
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
511
					break;		/* stop fetching */
512
				if (!seq->is_cycled)
513
				{
B
Bruce Momjian 已提交
514 515
					char		buf[100];

516
					snprintf(buf, sizeof(buf), INT64_FORMAT, maxv);
517
					ereport(ERROR,
B
Bruce Momjian 已提交
518 519 520
						  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
						   errmsg("nextval: reached maximum value of sequence \"%s\" (%s)",
								  RelationGetRelationName(seqrel), buf)));
521
				}
522 523 524 525 526 527 528
				next = minv;
			}
			else
				next += incby;
		}
		else
		{
529
			/* descending sequence */
530 531 532 533
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
534
					break;		/* stop fetching */
535
				if (!seq->is_cycled)
536
				{
B
Bruce Momjian 已提交
537 538
					char		buf[100];

539
					snprintf(buf, sizeof(buf), INT64_FORMAT, minv);
540
					ereport(ERROR,
B
Bruce Momjian 已提交
541 542 543
						  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
						   errmsg("nextval: reached minimum value of sequence \"%s\" (%s)",
								  RelationGetRelationName(seqrel), buf)));
544
				}
545 546 547 548 549
				next = maxv;
			}
			else
				next += incby;
		}
V
Vadim B. Mikheev 已提交
550 551 552 553 554 555
		fetch--;
		if (rescnt < cache)
		{
			log--;
			rescnt++;
			last = next;
B
Bruce Momjian 已提交
556 557
			if (rescnt == 1)	/* if it's first result - */
				result = next;	/* it's what to return */
V
Vadim B. Mikheev 已提交
558
		}
559 560
	}

561 562 563
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

564 565
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
566 567
	elm->cached = last;			/* last fetched number */

568 569
	last_used_seq = elm;

570
	START_CRIT_SECTION();
571

572 573
	MarkBufferDirty(buf);

574 575
	/* XLOG stuff */
	if (logit && !seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
576 577 578
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
579
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
580

581
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
582
		rdata[0].data = (char *) &xlrec;
583
		rdata[0].len = sizeof(xl_seq_rec);
584
		rdata[0].buffer = InvalidBuffer;
585 586
		rdata[0].next = &(rdata[1]);

587
		/* set values that will be saved in xlog */
588
		seq->last_value = next;
589
		seq->is_called = true;
590
		seq->log_cnt = 0;
591

B
Bruce Momjian 已提交
592 593 594
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
595
		rdata[1].buffer = InvalidBuffer;
596 597
		rdata[1].next = NULL;

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

600
		PageSetLSN(page, recptr);
601
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
602
	}
603

604
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
605
	seq->last_value = last;		/* last fetched number */
606
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
607
	seq->log_cnt = log;			/* how much is logged */
608

609
	END_CRIT_SECTION();
610

611
	UnlockReleaseBuffer(buf);
612

613 614
	relation_close(seqrel, NoLock);

615
	return result;
616 617
}

618
Datum
619
currval_oid(PG_FUNCTION_ARGS)
620
{
621 622
	Oid			relid = PG_GETARG_OID(0);
	int64		result;
623
	SeqTable	elm;
624
	Relation	seqrel;
625

V
Vadim B. Mikheev 已提交
626
	/* open and AccessShareLock sequence */
627
	init_sequence(relid, &elm, &seqrel);
628

629 630
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
631 632
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
633
				 errmsg("permission denied for sequence %s",
634
						RelationGetRelationName(seqrel))));
635

636
	if (elm->increment == 0)	/* nextval/read_info were not called */
637 638
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
639
				 errmsg("currval of sequence \"%s\" is not yet defined in this session",
640
						RelationGetRelationName(seqrel))));
641 642 643

	result = elm->last;

644 645
	relation_close(seqrel, NoLock);

646
	PG_RETURN_INT64(result);
647 648
}

649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
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")));

668
	seqrel = open_share_lock(last_used_seq);
669 670 671 672

	/* nextval() must have already been called for this sequence */
	Assert(last_used_seq->increment != 0);

673 674
	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)
675 676 677 678 679 680 681
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for sequence %s",
						RelationGetRelationName(seqrel))));

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

683 684 685
	PG_RETURN_INT64(result);
}

B
Bruce Momjian 已提交
686
/*
687 688 689 690
 * 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 已提交
691
 * work if multiple users are attached to the database and referencing
692 693
 * the sequence (unlikely if pg_dump is restoring it).
 *
B
Bruce Momjian 已提交
694
 * It is necessary to have the 3 arg version so that pg_dump can
695 696 697 698
 * 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 已提交
699
static void
700
do_setval(Oid relid, int64 next, bool iscalled)
M
 
Marc G. Fournier 已提交
701 702
{
	SeqTable	elm;
703
	Relation	seqrel;
704
	Buffer		buf;
705
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
706

707
	/* open and AccessShareLock sequence */
708
	init_sequence(relid, &elm, &seqrel);
709 710

	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
711 712
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
713
				 errmsg("permission denied for sequence %s",
714
						RelationGetRelationName(seqrel))));
M
 
Marc G. Fournier 已提交
715

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

719
	if ((next < seq->min_value) || (next > seq->max_value))
720
	{
B
Bruce Momjian 已提交
721 722 723 724
		char		bufv[100],
					bufm[100],
					bufx[100];

725 726 727
		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);
728 729
		ereport(ERROR,
				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
730
				 errmsg("setval: value %s is out of bounds for sequence \"%s\" (%s..%s)",
731 732
						bufv, RelationGetRelationName(seqrel),
						bufm, bufx)));
733
	}
M
 
Marc G. Fournier 已提交
734 735 736

	/* save info in local cache */
	elm->last = next;			/* last returned number */
B
Bruce Momjian 已提交
737
	elm->cached = next;			/* last cached number (forget cached values) */
M
 
Marc G. Fournier 已提交
738

739
	START_CRIT_SECTION();
740

741 742
	MarkBufferDirty(buf);

743 744
	/* XLOG stuff */
	if (!seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
745 746 747
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
748
		XLogRecData rdata[2];
749
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
750

751
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
752
		rdata[0].data = (char *) &xlrec;
753
		rdata[0].len = sizeof(xl_seq_rec);
754
		rdata[0].buffer = InvalidBuffer;
755 756
		rdata[0].next = &(rdata[1]);

757
		/* set values that will be saved in xlog */
758
		seq->last_value = next;
759
		seq->is_called = true;
760
		seq->log_cnt = 0;
761

B
Bruce Momjian 已提交
762 763 764
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
765
		rdata[1].buffer = InvalidBuffer;
766 767
		rdata[1].next = NULL;

768
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
769 770

		PageSetLSN(page, recptr);
771
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
772
	}
773

774 775
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
776
	seq->is_called = iscalled;
777
	seq->log_cnt = (iscalled) ? 0 : 1;
778

779
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
780

781
	UnlockReleaseBuffer(buf);
782 783

	relation_close(seqrel, NoLock);
784 785
}

786 787 788 789
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
790
Datum
791
setval_oid(PG_FUNCTION_ARGS)
792
{
793
	Oid			relid = PG_GETARG_OID(0);
794
	int64		next = PG_GETARG_INT64(1);
795

796
	do_setval(relid, next, true);
797

798
	PG_RETURN_INT64(next);
799 800
}

801 802 803 804
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
805
Datum
806
setval3_oid(PG_FUNCTION_ARGS)
807
{
808
	Oid			relid = PG_GETARG_OID(0);
809
	int64		next = PG_GETARG_INT64(1);
810 811
	bool		iscalled = PG_GETARG_BOOL(2);

812
	do_setval(relid, next, iscalled);
813

814
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
815 816
}

817

818
/*
819 820
 * Open the sequence and acquire AccessShareLock if needed
 *
821
 * If we haven't touched the sequence already in this transaction,
B
Bruce Momjian 已提交
822
 * we need to acquire AccessShareLock.	We arrange for the lock to
823 824 825
 * be owned by the top transaction, so that we don't need to do it
 * more than once per xact.
 */
826 827
static Relation
open_share_lock(SeqTable seq)
828
{
829
	LocalTransactionId thislxid = MyProc->lxid;
830

831
	/* Get the lock if not already held in this xact */
832
	if (seq->lxid != thislxid)
833 834 835 836 837 838 839
	{
		ResourceOwner currentOwner;

		currentOwner = CurrentResourceOwner;
		PG_TRY();
		{
			CurrentResourceOwner = TopTransactionResourceOwner;
840
			LockRelationOid(seq->relid, AccessShareLock);
841 842 843 844 845 846 847 848 849 850
		}
		PG_CATCH();
		{
			/* Ensure CurrentResourceOwner is restored on error */
			CurrentResourceOwner = currentOwner;
			PG_RE_THROW();
		}
		PG_END_TRY();
		CurrentResourceOwner = currentOwner;

851
		/* Flag that we have a lock in the current xact */
852
		seq->lxid = thislxid;
853
	}
854 855 856

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

859
/*
860
 * Given a relation OID, open and lock the sequence.  p_elm and p_rel are
861 862 863
 * output parameters.
 */
static void
864
init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel)
865
{
B
Bruce Momjian 已提交
866
	SeqTable	elm;
867
	Relation	seqrel;
868

869 870 871 872 873 874 875
	/* 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;
	}

876
	/*
877
	 * Allocate new seqtable entry if we didn't find one.
878
	 *
B
Bruce Momjian 已提交
879 880 881
	 * 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 已提交
882
	 */
883
	if (elm == NULL)
884
	{
885
		/*
B
Bruce Momjian 已提交
886 887
		 * Time to make a new seqtable entry.  These entries live as long as
		 * the backend does, so we use plain malloc for them.
888 889
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
890
		if (elm == NULL)
891 892 893
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
894
		elm->relid = relid;
895
		elm->lxid = InvalidLocalTransactionId;
896 897 898 899
		/* increment is set to 0 until we do read_info (see currval) */
		elm->last = elm->cached = elm->increment = 0;
		elm->next = seqtab;
		seqtab = elm;
900 901
	}

902 903 904 905 906 907 908 909 910 911
	/*
	 * 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))));
912 913 914

	*p_elm = elm;
	*p_rel = seqrel;
915 916 917
}


918 919
/* Given an opened relation, lock the page buffer and find the tuple */
static Form_pg_sequence
920
read_info(SeqTable elm, Relation rel, Buffer *buf)
921
{
922 923 924 925 926
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
	sequence_magic *sm;
	Form_pg_sequence seq;
927

928 929 930 931 932 933 934
	*buf = ReadBuffer(rel, 0);
	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);

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

	if (sm->magic != SEQ_MAGIC)
935 936
		elog(ERROR, "bad magic number in sequence \"%s\": %08X",
			 RelationGetRelationName(rel), sm->magic);
937 938 939 940 941 942 943 944 945 946

	lp = PageGetItemId(page, FirstOffsetNumber);
	Assert(ItemIdIsUsed(lp));
	tuple.t_data = (HeapTupleHeader) PageGetItem((Page) page, lp);

	seq = (Form_pg_sequence) GETSTRUCT(&tuple);

	elm->increment = seq->increment_by;

	return seq;
947 948
}

949 950
/*
 * init_params: process the options list of CREATE or ALTER SEQUENCE,
951 952
 * 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.
953 954 955 956
 *
 * If isInit is true, fill any unspecified options with default values;
 * otherwise, do not change existing options that aren't explicitly overridden.
 */
957
static void
958 959
init_params(List *options, bool isInit,
			Form_pg_sequence new, List **owned_by)
960
{
961 962 963 964 965
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
966
	DefElem    *is_cycled = NULL;
967
	ListCell   *option;
968

969 970
	*owned_by = NIL;

B
Bruce Momjian 已提交
971
	foreach(option, options)
972
	{
973
		DefElem    *defel = (DefElem *) lfirst(option);
974

975
		if (strcmp(defel->defname, "increment") == 0)
976 977
		{
			if (increment_by)
978 979 980
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
981
			increment_by = defel;
982
		}
B
Bruce Momjian 已提交
983

B
Bruce Momjian 已提交
984
		/*
B
Bruce Momjian 已提交
985
		 * start is for a new sequence restart is for alter
B
Bruce Momjian 已提交
986
		 */
987 988
		else if (strcmp(defel->defname, "start") == 0 ||
				 strcmp(defel->defname, "restart") == 0)
989 990
		{
			if (last_value)
991 992 993
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
994
			last_value = defel;
995
		}
996
		else if (strcmp(defel->defname, "maxvalue") == 0)
997 998
		{
			if (max_value)
999 1000 1001
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1002
			max_value = defel;
1003
		}
1004
		else if (strcmp(defel->defname, "minvalue") == 0)
1005 1006
		{
			if (min_value)
1007 1008 1009
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1010
			min_value = defel;
1011
		}
1012
		else if (strcmp(defel->defname, "cache") == 0)
1013 1014
		{
			if (cache_value)
1015 1016 1017
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1018
			cache_value = defel;
1019
		}
1020
		else if (strcmp(defel->defname, "cycle") == 0)
1021
		{
1022
			if (is_cycled)
1023 1024 1025
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1026
			is_cycled = defel;
1027
		}
1028 1029 1030 1031 1032 1033 1034 1035
		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);
		}
1036
		else
1037
			elog(ERROR, "option \"%s\" not recognized",
1038 1039 1040
				 defel->defname);
	}

B
Bruce Momjian 已提交
1041
	/* INCREMENT BY */
1042
	if (increment_by != NULL)
B
Bruce Momjian 已提交
1043 1044
	{
		new->increment_by = defGetInt64(increment_by);
1045 1046 1047
		if (new->increment_by == 0)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1048
					 errmsg("INCREMENT must not be zero")));
B
Bruce Momjian 已提交
1049
	}
1050 1051 1052 1053
	else if (isInit)
		new->increment_by = 1;

	/* CYCLE */
1054
	if (is_cycled != NULL)
1055 1056 1057 1058 1059 1060
	{
		new->is_cycled = intVal(is_cycled->arg);
		Assert(new->is_cycled == false || new->is_cycled == true);
	}
	else if (isInit)
		new->is_cycled = false;
1061

1062
	/* MAXVALUE (null arg means NO MAXVALUE) */
1063
	if (max_value != NULL && max_value->arg)
1064
		new->max_value = defGetInt64(max_value);
1065
	else if (isInit || max_value != NULL)
1066
	{
1067
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1068
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
1069
		else
B
Bruce Momjian 已提交
1070
			new->max_value = -1;	/* descending seq */
1071
	}
1072

1073
	/* MINVALUE (null arg means NO MINVALUE) */
1074
	if (min_value != NULL && min_value->arg)
1075
		new->min_value = defGetInt64(min_value);
1076
	else if (isInit || min_value != NULL)
1077
	{
1078
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1079
			new->min_value = 1; /* ascending seq */
1080
		else
B
Bruce Momjian 已提交
1081
			new->min_value = SEQ_MINVALUE;		/* descending seq */
1082
	}
1083

1084
	/* crosscheck min/max */
1085
	if (new->min_value >= new->max_value)
1086
	{
B
Bruce Momjian 已提交
1087 1088 1089
		char		bufm[100],
					bufx[100];

1090 1091
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
		snprintf(bufx, sizeof(bufx), INT64_FORMAT, new->max_value);
1092 1093 1094 1095
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("MINVALUE (%s) must be less than MAXVALUE (%s)",
						bufm, bufx)));
1096
	}
1097

B
Bruce Momjian 已提交
1098
	/* START WITH */
1099
	if (last_value != NULL)
1100
	{
1101
		new->last_value = defGetInt64(last_value);
1102 1103 1104
		new->is_called = false;
		new->log_cnt = 1;
	}
1105
	else if (isInit)
1106
	{
1107 1108 1109 1110
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
1111 1112
		new->is_called = false;
		new->log_cnt = 1;
1113
	}
1114

1115
	/* crosscheck */
1116
	if (new->last_value < new->min_value)
1117
	{
B
Bruce Momjian 已提交
1118 1119 1120
		char		bufs[100],
					bufm[100];

1121 1122
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
1123 1124
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1125
				 errmsg("START value (%s) cannot be less than MINVALUE (%s)",
B
Bruce Momjian 已提交
1126
						bufs, bufm)));
1127
	}
1128
	if (new->last_value > new->max_value)
1129
	{
B
Bruce Momjian 已提交
1130 1131 1132
		char		bufs[100],
					bufm[100];

1133 1134
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
1135 1136
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1137
			   errmsg("START value (%s) cannot be greater than MAXVALUE (%s)",
B
Bruce Momjian 已提交
1138
					  bufs, bufm)));
1139
	}
1140

B
Bruce Momjian 已提交
1141
	/* CACHE */
1142
	if (cache_value != NULL)
1143
	{
1144 1145 1146 1147
		new->cache_value = defGetInt64(cache_value);
		if (new->cache_value <= 0)
		{
			char		buf[100];
B
Bruce Momjian 已提交
1148

1149 1150 1151 1152 1153 1154
			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)));
		}
1155
	}
1156 1157
	else if (isInit)
		new->cache_value = 1;
1158 1159
}

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
/*
 * 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 已提交
1184
				errhint("Specify OWNED BY table.column or OWNED BY NONE.")));
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
		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),
P
Peter Eisentraut 已提交
1213
			errmsg("sequence must have same owner as table it is linked to")));
1214 1215 1216
		if (RelationGetNamespace(seqrel) != RelationGetNamespace(tablerel))
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
P
Peter Eisentraut 已提交
1217
					 errmsg("sequence must be in same schema as table it is linked to")));
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228

		/* 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 已提交
1229 1230
	 * OK, we are ready to update pg_depend.  First remove any existing AUTO
	 * dependencies for the sequence, then optionally add a new one.
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	 */
	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 已提交
1253

B
Bruce Momjian 已提交
1254 1255
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
1256
{
B
Bruce Momjian 已提交
1257 1258 1259 1260 1261 1262 1263
	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);
1264
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
1265

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

1269
	reln = XLogOpenRelation(xlrec->node);
1270 1271
	buffer = XLogReadBuffer(reln, 0, true);
	Assert(BufferIsValid(buffer));
V
Vadim B. Mikheev 已提交
1272 1273
	page = (Page) BufferGetPage(buffer);

1274 1275
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
1276 1277 1278
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
1279

B
Bruce Momjian 已提交
1280
	item = (char *) xlrec + sizeof(xl_seq_rec);
1281 1282
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
1283
	if (PageAddItem(page, (Item) item, itemsz,
1284
					FirstOffsetNumber, LP_USED) == InvalidOffsetNumber)
1285
		elog(PANIC, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
1286 1287

	PageSetLSN(page, lsn);
1288
	PageSetTLI(page, ThisTimeLineID);
1289 1290
	MarkBufferDirty(buffer);
	UnlockReleaseBuffer(buffer);
V
Vadim B. Mikheev 已提交
1291 1292
}

B
Bruce Momjian 已提交
1293
void
1294
seq_desc(StringInfo buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
1295
{
B
Bruce Momjian 已提交
1296 1297
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
1298 1299

	if (info == XLOG_SEQ_LOG)
1300
		appendStringInfo(buf, "log: ");
V
Vadim B. Mikheev 已提交
1301 1302
	else
	{
1303
		appendStringInfo(buf, "UNKNOWN");
V
Vadim B. Mikheev 已提交
1304 1305 1306
		return;
	}

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