sequence.c 34.9 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.149 2008/01/01 19:45:49 momjian 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
	bool		last_valid;		/* do we have a valid "last" value? */
69 70 71 72
	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 */
73
	/* note that increment is zero until we first do read_info() */
74
} SeqTableData;
75 76 77

typedef SeqTableData *SeqTable;

78
static SeqTable seqtab = NULL;	/* Head of list of SeqTable items */
79

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

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

95 96

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

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

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

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

136 137 138 139
		null[i - 1] = ' ';

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

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

197
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
198

199
	rel = heap_open(seqoid, AccessExclusiveLock);
200
	tupDesc = RelationGetDescr(rel);
201

202 203
	/* Initialize first page of relation with special magic number */

204
	buf = ReadBuffer(rel, P_NEW);
205 206
	Assert(BufferGetBlockNumber(buf) == 0);

207 208 209 210 211 212
	page = (PageHeader) BufferGetPage(buf);

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

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

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

220 221
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

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

239
	START_CRIT_SECTION();
240 241 242

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

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

255
		HeapTupleHeaderSetXmin((HeapTupleHeader) item, FrozenTransactionId);
256 257
		((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;

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

262 263
	MarkBufferDirty(buf);

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

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

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

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

288
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
289 290

		PageSetLSN(page, recptr);
291
		PageSetTLI(page, ThisTimeLineID);
292
	}
293

294
	END_CRIT_SECTION();
295

296 297
	UnlockReleaseBuffer(buf);

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

302
	heap_close(rel, NoLock);
303 304
}

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

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

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

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

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

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

341 342 343 344
	/* 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;

345
	/* Now okay to update the on-disk tuple */
346
	memcpy(seq, &new, sizeof(FormData_pg_sequence));
B
Bruce Momjian 已提交
347 348 349

	START_CRIT_SECTION();

350 351
	MarkBufferDirty(buf);

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

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

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

	END_CRIT_SECTION();

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

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

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

388

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

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

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

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

455
	/* lock page' buffer and read tuple */
456
	seq = read_info(elm, seqrel, &buf);
457
	page = BufferGetPage(buf);
458

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

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

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

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

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

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

564 565 566
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

567 568
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
569
	elm->cached = last;			/* last fetched number */
570
	elm->last_valid = true;
V
Vadim B. Mikheev 已提交
571

572 573
	last_used_seq = elm;

574
	START_CRIT_SECTION();
575

576 577
	MarkBufferDirty(buf);

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

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

591
		/* set values that will be saved in xlog */
592
		seq->last_value = next;
593
		seq->is_called = true;
594
		seq->log_cnt = 0;
595

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

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

604
		PageSetLSN(page, recptr);
605
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
606
	}
607

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

613
	END_CRIT_SECTION();
614

615
	UnlockReleaseBuffer(buf);
616

617 618
	relation_close(seqrel, NoLock);

619
	return result;
620 621
}

622
Datum
623
currval_oid(PG_FUNCTION_ARGS)
624
{
625 626
	Oid			relid = PG_GETARG_OID(0);
	int64		result;
627
	SeqTable	elm;
628
	Relation	seqrel;
629

V
Vadim B. Mikheev 已提交
630
	/* open and AccessShareLock sequence */
631
	init_sequence(relid, &elm, &seqrel);
632

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

640
	if (!elm->last_valid)
641 642
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
643
				 errmsg("currval of sequence \"%s\" is not yet defined in this session",
644
						RelationGetRelationName(seqrel))));
645 646 647

	result = elm->last;

648 649
	relation_close(seqrel, NoLock);

650
	PG_RETURN_INT64(result);
651 652
}

653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
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")));

672
	seqrel = open_share_lock(last_used_seq);
673 674

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

677 678
	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)
679 680 681 682 683 684 685
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for sequence %s",
						RelationGetRelationName(seqrel))));

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

687 688 689
	PG_RETURN_INT64(result);
}

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

711
	/* open and AccessShareLock sequence */
712
	init_sequence(relid, &elm, &seqrel);
713 714

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

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

723
	if ((next < seq->min_value) || (next > seq->max_value))
724
	{
B
Bruce Momjian 已提交
725 726 727 728
		char		bufv[100],
					bufm[100],
					bufx[100];

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

739 740 741 742 743 744 745 746 747
	/* 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 已提交
748

749
	START_CRIT_SECTION();
750

751 752
	MarkBufferDirty(buf);

753 754
	/* XLOG stuff */
	if (!seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
755 756 757
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
758
		XLogRecData rdata[2];
759
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
760

761
		xlrec.node = seqrel->rd_node;
B
Bruce Momjian 已提交
762
		rdata[0].data = (char *) &xlrec;
763
		rdata[0].len = sizeof(xl_seq_rec);
764
		rdata[0].buffer = InvalidBuffer;
765 766
		rdata[0].next = &(rdata[1]);

767
		/* set values that will be saved in xlog */
768
		seq->last_value = next;
769
		seq->is_called = true;
770
		seq->log_cnt = 0;
771

B
Bruce Momjian 已提交
772 773 774
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
775
		rdata[1].buffer = InvalidBuffer;
776 777
		rdata[1].next = NULL;

778
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG, rdata);
779 780

		PageSetLSN(page, recptr);
781
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
782
	}
783

784 785
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
786
	seq->is_called = iscalled;
787
	seq->log_cnt = (iscalled) ? 0 : 1;
788

789
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
790

791
	UnlockReleaseBuffer(buf);
792 793

	relation_close(seqrel, NoLock);
794 795
}

796 797 798 799
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
800
Datum
801
setval_oid(PG_FUNCTION_ARGS)
802
{
803
	Oid			relid = PG_GETARG_OID(0);
804
	int64		next = PG_GETARG_INT64(1);
805

806
	do_setval(relid, next, true);
807

808
	PG_RETURN_INT64(next);
809 810
}

811 812 813 814
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
815
Datum
816
setval3_oid(PG_FUNCTION_ARGS)
817
{
818
	Oid			relid = PG_GETARG_OID(0);
819
	int64		next = PG_GETARG_INT64(1);
820 821
	bool		iscalled = PG_GETARG_BOOL(2);

822
	do_setval(relid, next, iscalled);
823

824
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
825 826
}

827

828
/*
829 830
 * Open the sequence and acquire AccessShareLock if needed
 *
831
 * If we haven't touched the sequence already in this transaction,
B
Bruce Momjian 已提交
832
 * we need to acquire AccessShareLock.	We arrange for the lock to
833 834 835
 * be owned by the top transaction, so that we don't need to do it
 * more than once per xact.
 */
836 837
static Relation
open_share_lock(SeqTable seq)
838
{
839
	LocalTransactionId thislxid = MyProc->lxid;
840

841
	/* Get the lock if not already held in this xact */
842
	if (seq->lxid != thislxid)
843 844 845 846 847 848 849
	{
		ResourceOwner currentOwner;

		currentOwner = CurrentResourceOwner;
		PG_TRY();
		{
			CurrentResourceOwner = TopTransactionResourceOwner;
850
			LockRelationOid(seq->relid, AccessShareLock);
851 852 853 854 855 856 857 858 859 860
		}
		PG_CATCH();
		{
			/* Ensure CurrentResourceOwner is restored on error */
			CurrentResourceOwner = currentOwner;
			PG_RE_THROW();
		}
		PG_END_TRY();
		CurrentResourceOwner = currentOwner;

861
		/* Flag that we have a lock in the current xact */
862
		seq->lxid = thislxid;
863
	}
864 865 866

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

869
/*
870
 * Given a relation OID, open and lock the sequence.  p_elm and p_rel are
871 872 873
 * output parameters.
 */
static void
874
init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel)
875
{
B
Bruce Momjian 已提交
876
	SeqTable	elm;
877
	Relation	seqrel;
878

879 880 881 882 883 884 885
	/* 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;
	}

886
	/*
887
	 * Allocate new seqtable entry if we didn't find one.
888
	 *
B
Bruce Momjian 已提交
889 890 891
	 * 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 已提交
892
	 */
893
	if (elm == NULL)
894
	{
895
		/*
B
Bruce Momjian 已提交
896 897
		 * Time to make a new seqtable entry.  These entries live as long as
		 * the backend does, so we use plain malloc for them.
898 899
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
900
		if (elm == NULL)
901 902 903
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
904
		elm->relid = relid;
905
		elm->lxid = InvalidLocalTransactionId;
906
		elm->last_valid = false;
907 908 909
		elm->last = elm->cached = elm->increment = 0;
		elm->next = seqtab;
		seqtab = elm;
910 911
	}

912 913 914 915 916 917 918 919 920 921
	/*
	 * 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))));
922 923 924

	*p_elm = elm;
	*p_rel = seqrel;
925 926 927
}


928 929
/* Given an opened relation, lock the page buffer and find the tuple */
static Form_pg_sequence
930
read_info(SeqTable elm, Relation rel, Buffer *buf)
931
{
932 933 934 935 936
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
	sequence_magic *sm;
	Form_pg_sequence seq;
937

938 939 940 941 942 943 944
	*buf = ReadBuffer(rel, 0);
	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);

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

	if (sm->magic != SEQ_MAGIC)
945 946
		elog(ERROR, "bad magic number in sequence \"%s\": %08X",
			 RelationGetRelationName(rel), sm->magic);
947 948

	lp = PageGetItemId(page, FirstOffsetNumber);
949
	Assert(ItemIdIsNormal(lp));
950 951
	tuple.t_data = (HeapTupleHeader) PageGetItem((Page) page, lp);

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
	/*
	 * Previous releases of Postgres neglected to prevent SELECT FOR UPDATE
	 * on a sequence, which would leave a non-frozen XID in the sequence
	 * tuple's xmax, which eventually leads to clog access failures or worse.
	 * If we see this has happened, clean up after it.  We treat this like a
	 * hint bit update, ie, don't bother to WAL-log it, since we can certainly
	 * do this again if the update gets lost.
	 */
	if (HeapTupleHeaderGetXmax(tuple.t_data) != InvalidTransactionId)
	{
		HeapTupleHeaderSetXmax(tuple.t_data, InvalidTransactionId);
		tuple.t_data->t_infomask &= ~HEAP_XMAX_COMMITTED;
		tuple.t_data->t_infomask |= HEAP_XMAX_INVALID;
		SetBufferCommitInfoNeedsSave(*buf);
	}

968 969
	seq = (Form_pg_sequence) GETSTRUCT(&tuple);

970
	/* this is a handy place to update our copy of the increment */
971 972 973
	elm->increment = seq->increment_by;

	return seq;
974 975
}

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

996 997
	*owned_by = NIL;

B
Bruce Momjian 已提交
998
	foreach(option, options)
999
	{
1000
		DefElem    *defel = (DefElem *) lfirst(option);
1001

1002
		if (strcmp(defel->defname, "increment") == 0)
1003 1004
		{
			if (increment_by)
1005 1006 1007
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1008
			increment_by = defel;
1009
		}
B
Bruce Momjian 已提交
1010

B
Bruce Momjian 已提交
1011
		/*
B
Bruce Momjian 已提交
1012
		 * start is for a new sequence restart is for alter
B
Bruce Momjian 已提交
1013
		 */
1014 1015
		else if (strcmp(defel->defname, "start") == 0 ||
				 strcmp(defel->defname, "restart") == 0)
1016 1017
		{
			if (last_value)
1018 1019 1020
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1021
			last_value = defel;
1022
		}
1023
		else if (strcmp(defel->defname, "maxvalue") == 0)
1024 1025
		{
			if (max_value)
1026 1027 1028
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1029
			max_value = defel;
1030
		}
1031
		else if (strcmp(defel->defname, "minvalue") == 0)
1032 1033
		{
			if (min_value)
1034 1035 1036
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1037
			min_value = defel;
1038
		}
1039
		else if (strcmp(defel->defname, "cache") == 0)
1040 1041
		{
			if (cache_value)
1042 1043 1044
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1045
			cache_value = defel;
1046
		}
1047
		else if (strcmp(defel->defname, "cycle") == 0)
1048
		{
1049
			if (is_cycled)
1050 1051 1052
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1053
			is_cycled = defel;
1054
		}
1055 1056 1057 1058 1059 1060 1061 1062
		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);
		}
1063
		else
1064
			elog(ERROR, "option \"%s\" not recognized",
1065 1066 1067
				 defel->defname);
	}

B
Bruce Momjian 已提交
1068
	/* INCREMENT BY */
1069
	if (increment_by != NULL)
B
Bruce Momjian 已提交
1070 1071
	{
		new->increment_by = defGetInt64(increment_by);
1072 1073 1074
		if (new->increment_by == 0)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1075
					 errmsg("INCREMENT must not be zero")));
B
Bruce Momjian 已提交
1076
	}
1077 1078 1079 1080
	else if (isInit)
		new->increment_by = 1;

	/* CYCLE */
1081
	if (is_cycled != NULL)
1082 1083 1084 1085 1086 1087
	{
		new->is_cycled = intVal(is_cycled->arg);
		Assert(new->is_cycled == false || new->is_cycled == true);
	}
	else if (isInit)
		new->is_cycled = false;
1088

1089
	/* MAXVALUE (null arg means NO MAXVALUE) */
1090
	if (max_value != NULL && max_value->arg)
1091
		new->max_value = defGetInt64(max_value);
1092
	else if (isInit || max_value != NULL)
1093
	{
1094
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1095
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
1096
		else
B
Bruce Momjian 已提交
1097
			new->max_value = -1;	/* descending seq */
1098
	}
1099

1100
	/* MINVALUE (null arg means NO MINVALUE) */
1101
	if (min_value != NULL && min_value->arg)
1102
		new->min_value = defGetInt64(min_value);
1103
	else if (isInit || min_value != NULL)
1104
	{
1105
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1106
			new->min_value = 1; /* ascending seq */
1107
		else
B
Bruce Momjian 已提交
1108
			new->min_value = SEQ_MINVALUE;		/* descending seq */
1109
	}
1110

1111
	/* crosscheck min/max */
1112
	if (new->min_value >= new->max_value)
1113
	{
B
Bruce Momjian 已提交
1114 1115 1116
		char		bufm[100],
					bufx[100];

1117 1118
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
		snprintf(bufx, sizeof(bufx), INT64_FORMAT, new->max_value);
1119 1120 1121 1122
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("MINVALUE (%s) must be less than MAXVALUE (%s)",
						bufm, bufx)));
1123
	}
1124

B
Bruce Momjian 已提交
1125
	/* START WITH */
1126
	if (last_value != NULL)
1127
	{
1128
		new->last_value = defGetInt64(last_value);
1129 1130 1131
		new->is_called = false;
		new->log_cnt = 1;
	}
1132
	else if (isInit)
1133
	{
1134 1135 1136 1137
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
1138 1139
		new->is_called = false;
		new->log_cnt = 1;
1140
	}
1141

1142
	/* crosscheck */
1143
	if (new->last_value < new->min_value)
1144
	{
B
Bruce Momjian 已提交
1145 1146 1147
		char		bufs[100],
					bufm[100];

1148 1149
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
1150 1151
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1152
				 errmsg("START value (%s) cannot be less than MINVALUE (%s)",
B
Bruce Momjian 已提交
1153
						bufs, bufm)));
1154
	}
1155
	if (new->last_value > new->max_value)
1156
	{
B
Bruce Momjian 已提交
1157 1158 1159
		char		bufs[100],
					bufm[100];

1160 1161
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
1162 1163
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
B
Bruce Momjian 已提交
1164 1165
			  errmsg("START value (%s) cannot be greater than MAXVALUE (%s)",
					 bufs, bufm)));
1166
	}
1167

B
Bruce Momjian 已提交
1168
	/* CACHE */
1169
	if (cache_value != NULL)
1170
	{
1171 1172 1173 1174
		new->cache_value = defGetInt64(cache_value);
		if (new->cache_value <= 0)
		{
			char		buf[100];
B
Bruce Momjian 已提交
1175

1176 1177 1178 1179 1180 1181
			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)));
		}
1182
	}
1183 1184
	else if (isInit)
		new->cache_value = 1;
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
/*
 * 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 已提交
1211
				errhint("Specify OWNED BY table.column or OWNED BY NONE.")));
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
		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 已提交
1240
					 errmsg("sequence must have same owner as table it is linked to")));
1241 1242 1243
		if (RelationGetNamespace(seqrel) != RelationGetNamespace(tablerel))
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
P
Peter Eisentraut 已提交
1244
					 errmsg("sequence must be in same schema as table it is linked to")));
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

		/* 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 已提交
1256 1257
	 * OK, we are ready to update pg_depend.  First remove any existing AUTO
	 * dependencies for the sequence, then optionally add a new one.
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
	 */
	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 已提交
1280

B
Bruce Momjian 已提交
1281 1282
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
1283
{
B
Bruce Momjian 已提交
1284 1285 1286 1287 1288 1289 1290
	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);
1291
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
1292

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

1296
	reln = XLogOpenRelation(xlrec->node);
1297 1298
	buffer = XLogReadBuffer(reln, 0, true);
	Assert(BufferIsValid(buffer));
V
Vadim B. Mikheev 已提交
1299 1300
	page = (Page) BufferGetPage(buffer);

1301 1302
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
1303 1304 1305
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
1306

B
Bruce Momjian 已提交
1307
	item = (char *) xlrec + sizeof(xl_seq_rec);
1308 1309
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
1310
	if (PageAddItem(page, (Item) item, itemsz,
1311
					FirstOffsetNumber, false, false) == InvalidOffsetNumber)
1312
		elog(PANIC, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
1313 1314

	PageSetLSN(page, lsn);
1315
	PageSetTLI(page, ThisTimeLineID);
1316 1317
	MarkBufferDirty(buffer);
	UnlockReleaseBuffer(buffer);
V
Vadim B. Mikheev 已提交
1318 1319
}

B
Bruce Momjian 已提交
1320
void
1321
seq_desc(StringInfo buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
1322
{
B
Bruce Momjian 已提交
1323 1324
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
1325 1326

	if (info == XLOG_SEQ_LOG)
1327
		appendStringInfo(buf, "log: ");
V
Vadim B. Mikheev 已提交
1328 1329
	else
	{
1330
		appendStringInfo(buf, "UNKNOWN");
V
Vadim B. Mikheev 已提交
1331 1332 1333
		return;
	}

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