sequence.c 23.5 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
11
 *	  $Header: /cvsroot/pgsql/src/backend/commands/sequence.c,v 1.82 2002/06/20 20:29:27 momjian Exp $
12
 *
13 14
 *-------------------------------------------------------------------------
 */
15
#include "postgres.h"
16

17
#include "access/heapam.h"
18
#include "catalog/namespace.h"
19
#include "catalog/pg_type.h"
20
#include "commands/defrem.h"
21
#include "commands/tablecmds.h"
22
#include "commands/sequence.h"
B
Bruce Momjian 已提交
23
#include "miscadmin.h"
24
#include "utils/acl.h"
B
Bruce Momjian 已提交
25
#include "utils/builtins.h"
26

27

28 29 30 31 32 33
#ifndef INT64_IS_BUSTED
#ifdef HAVE_LL_CONSTANTS
#define SEQ_MAXVALUE	((int64) 0x7FFFFFFFFFFFFFFFLL)
#else
#define SEQ_MAXVALUE	((int64) 0x7FFFFFFFFFFFFFFF)
#endif
34
#else							/* INT64_IS_BUSTED */
35
#define SEQ_MAXVALUE	((int64) 0x7FFFFFFF)
36
#endif   /* INT64_IS_BUSTED */
37 38

#define SEQ_MINVALUE	(-SEQ_MAXVALUE)
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 63 64 65 66
/*
 * 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.)
 *
 * XXX We use linear search to find pre-existing SeqTable entries.  This is
 * 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 71 72 73 74 75
	struct SeqTableData *next;	/* link to next SeqTable object */
	Oid			relid;			/* pg_class OID of this sequence */
	TransactionId xid;			/* xact in which we last did a seq op */
	int64		last;			/* value last returned by nextval */
	int64		cached;			/* last value already cached for nextval */
	/* if last != cached, we have not used up all the cached values */
	int64		increment;		/* copy of sequence's increment field */
76
} SeqTableData;
77 78 79

typedef SeqTableData *SeqTable;

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

82 83 84 85 86

static void init_sequence(const char *caller, RangeVar *relation,
						  SeqTable *p_elm, Relation *p_rel);
static Form_pg_sequence read_info(const char *caller, SeqTable elm,
								  Relation rel, Buffer *buf);
87
static void init_params(CreateSeqStmt *seq, Form_pg_sequence new);
88
static void do_setval(RangeVar *sequence, int64 next, bool iscalled);
89 90

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

	/* Check and set values */
	init_params(seq, &new);

	/*
115
	 * Create relation (and fill *null & *value)
116 117 118
	 */
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
119
	{
120 121 122
		ColumnDef  *coldef;
		TypeName   *typnam;

123 124
		typnam = makeNode(TypeName);
		typnam->setof = FALSE;
125
		typnam->arrayBounds = NIL;
B
Bruce Momjian 已提交
126
		typnam->typmod = -1;
127 128
		coldef = makeNode(ColumnDef);
		coldef->typename = typnam;
129 130
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
131 132 133 134 135
		coldef->is_not_null = false;
		null[i - 1] = ' ';

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

186 187
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
188
	stmt->constraints = NIL;
189
	stmt->hasoids = false;
190

191
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
192

193
	rel = heap_open(seqoid, AccessExclusiveLock);
194
	tupDesc = RelationGetDescr(rel);
195

196 197
	/* Initialize first page of relation with special magic number */

198 199 200
	buf = ReadBuffer(rel, P_NEW);

	if (!BufferIsValid(buf))
201
		elog(ERROR, "DefineSequence: ReadBuffer failed");
202

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 223 224 225 226 227 228 229 230 231 232 233
	 * Two special hacks here:
	 *
	 * 1. Since VACUUM does not process sequences, we have to force the tuple
	 * to have xmin = FrozenTransactionId now.  Otherwise it would become
	 * invisible to SELECTs after 2G transactions.  It is okay to do this
	 * because if the current transaction aborts, no other xact will ever
	 * examine the sequence tuple anyway.
	 *
	 * 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
	START_CRIT_SECTION();
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

	{
		/*
		 * 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.
		 */
		ItemId		itemId;
		Item		item;

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

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

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

259
	{
260 261 262 263
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];
		Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
264 265

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

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

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

		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);

		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
	}
	END_CRIT_SECTION();
287

288
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);
289 290
	WriteBuffer(buf);
	heap_close(rel, NoLock);
291 292 293
}


294 295
Datum
nextval(PG_FUNCTION_ARGS)
296
{
297
	text	   *seqin = PG_GETARG_TEXT_P(0);
298
	RangeVar   *sequence;
299
	SeqTable	elm;
300
	Relation	seqrel;
301
	Buffer		buf;
302
	Page		page;
303
	Form_pg_sequence seq;
304
	int64		incby,
305 306
				maxv,
				minv,
V
Vadim B. Mikheev 已提交
307 308 309 310
				cache,
				log,
				fetch,
				last;
311
	int64		result,
312 313
				next,
				rescnt = 0;
V
Vadim B. Mikheev 已提交
314
	bool		logit = false;
315

316 317 318
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
																"nextval"));

V
Vadim B. Mikheev 已提交
319
	/* open and AccessShareLock sequence */
320
	init_sequence("nextval", sequence, &elm, &seqrel);
321

322 323
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
		elog(ERROR, "%s.nextval: you don't have permissions to set sequence %s",
324
			 sequence->relname, sequence->relname);
325 326 327 328

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
		elm->last += elm->increment;
329
		relation_close(seqrel, NoLock);
330
		PG_RETURN_INT64(elm->last);
331
	}
332

333 334
	/* lock page' buffer and read tuple */
	seq = read_info("nextval", elm, seqrel, &buf);
335
	page = BufferGetPage(buf);
336

V
Vadim B. Mikheev 已提交
337
	last = next = result = seq->last_value;
338 339 340
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
341 342
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
343

344
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
345
	{
346
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
347 348 349
		fetch--;
		log--;
	}
350

351 352 353 354 355 356 357 358 359 360
	/*
	 * 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.)
	 *
	 * 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.
	 */
V
Vadim B. Mikheev 已提交
361 362
	if (log < fetch)
	{
363 364
		/* forced log to satisfy local demand for values */
		fetch = log = fetch + SEQ_LOG_VALS;
V
Vadim B. Mikheev 已提交
365 366
		logit = true;
	}
367 368 369 370 371 372 373 374 375 376 377
	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 已提交
378

B
Bruce Momjian 已提交
379
	while (fetch)				/* try to fetch cache [+ log ] numbers */
380
	{
381 382 383 384
		/*
		 * Check MAXVALUE for ascending sequences and MINVALUE for
		 * descending sequences
		 */
385
		if (incby > 0)
386
		{
387
			/* ascending sequence */
388 389 390 391
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
392
					break;		/* stop fetching */
393 394
				if (!seq->is_cycled)
					elog(ERROR, "%s.nextval: reached MAXVALUE (" INT64_FORMAT ")",
395
						 sequence->relname, maxv);
396 397 398 399 400 401 402
				next = minv;
			}
			else
				next += incby;
		}
		else
		{
403
			/* descending sequence */
404 405 406 407
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
408
					break;		/* stop fetching */
409 410
				if (!seq->is_cycled)
					elog(ERROR, "%s.nextval: reached MINVALUE (" INT64_FORMAT ")",
411
						 sequence->relname, minv);
412 413 414 415 416
				next = maxv;
			}
			else
				next += incby;
		}
V
Vadim B. Mikheev 已提交
417 418 419 420 421 422
		fetch--;
		if (rescnt < cache)
		{
			log--;
			rescnt++;
			last = next;
B
Bruce Momjian 已提交
423 424
			if (rescnt == 1)	/* if it's first result - */
				result = next;	/* it's what to return */
V
Vadim B. Mikheev 已提交
425
		}
426 427
	}

428 429 430
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

431 432
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
433 434
	elm->cached = last;			/* last fetched number */

435
	START_CRIT_SECTION();
V
Vadim B. Mikheev 已提交
436 437 438 439
	if (logit)
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
440
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
441

442
		xlrec.node = seqrel->rd_node;
443
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
444
		rdata[0].data = (char *) &xlrec;
445 446 447 448
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

		seq->last_value = next;
449
		seq->is_called = true;
450 451
		seq->log_cnt = 0;
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
452 453 454
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
455 456
		rdata[1].next = NULL;

B
Bruce Momjian 已提交
457
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);
V
Vadim B. Mikheev 已提交
458

459 460
		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
461
	}
462

463
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
464
	seq->last_value = last;		/* last fetched number */
465
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
466
	seq->log_cnt = log;			/* how much is logged */
467
	END_CRIT_SECTION();
468

V
Vadim B. Mikheev 已提交
469 470
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

B
Bruce Momjian 已提交
471
	WriteBuffer(buf);
472

473 474
	relation_close(seqrel, NoLock);

475
	PG_RETURN_INT64(result);
476 477
}

478 479
Datum
currval(PG_FUNCTION_ARGS)
480
{
481
	text	   *seqin = PG_GETARG_TEXT_P(0);
482
	RangeVar   *sequence;
483
	SeqTable	elm;
484
	Relation	seqrel;
485
	int64		result;
486

487 488 489
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
																"currval"));

V
Vadim B. Mikheev 已提交
490
	/* open and AccessShareLock sequence */
491
	init_sequence("currval", sequence, &elm, &seqrel);
492

493 494
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK)
		elog(ERROR, "%s.currval: you don't have permissions to read sequence %s",
495
			 sequence->relname, sequence->relname);
496

497
	if (elm->increment == 0)	/* nextval/read_info were not called */
498
		elog(ERROR, "%s.currval is not yet defined in this session",
499
			 sequence->relname);
500 501 502

	result = elm->last;

503 504
	relation_close(seqrel, NoLock);

505
	PG_RETURN_INT64(result);
506 507
}

B
Bruce Momjian 已提交
508
/*
509 510 511 512
 * 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 已提交
513
 * work if multiple users are attached to the database and referencing
514 515
 * the sequence (unlikely if pg_dump is restoring it).
 *
B
Bruce Momjian 已提交
516
 * It is necessary to have the 3 arg version so that pg_dump can
517 518 519 520
 * 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 已提交
521
static void
522
do_setval(RangeVar *sequence, int64 next, bool iscalled)
M
 
Marc G. Fournier 已提交
523 524
{
	SeqTable	elm;
525
	Relation	seqrel;
526
	Buffer		buf;
527
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
528

529
	/* open and AccessShareLock sequence */
530
	init_sequence("setval", sequence, &elm, &seqrel);
531 532

	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
M
 
Marc G. Fournier 已提交
533
		elog(ERROR, "%s.setval: you don't have permissions to set sequence %s",
534
			 sequence->relname, sequence->relname);
M
 
Marc G. Fournier 已提交
535

536
	/* lock page' buffer and read tuple */
537
	seq = read_info("setval", elm, seqrel, &buf);
M
 
Marc G. Fournier 已提交
538

539
	if ((next < seq->min_value) || (next > seq->max_value))
540
		elog(ERROR, "%s.setval: value " INT64_FORMAT " is out of bounds (" INT64_FORMAT "," INT64_FORMAT ")",
541
			 sequence->relname, next, seq->min_value, seq->max_value);
M
 
Marc G. Fournier 已提交
542 543 544

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

548
	START_CRIT_SECTION();
V
Vadim B. Mikheev 已提交
549 550 551
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
552
		XLogRecData rdata[2];
553
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
554

555
		xlrec.node = seqrel->rd_node;
556
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
557
		rdata[0].data = (char *) &xlrec;
558 559 560 561
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

		seq->last_value = next;
562
		seq->is_called = true;
563 564
		seq->log_cnt = 0;
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
565 566 567
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
568 569
		rdata[1].next = NULL;

B
Bruce Momjian 已提交
570
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);
571 572 573

		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
574
	}
575 576
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
577
	seq->is_called = iscalled;
578
	seq->log_cnt = (iscalled) ? 0 : 1;
579
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
580

V
Vadim B. Mikheev 已提交
581 582
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

B
Bruce Momjian 已提交
583
	WriteBuffer(buf);
584 585

	relation_close(seqrel, NoLock);
586 587
}

588 589 590 591
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
592 593 594 595
Datum
setval(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
596
	int64		next = PG_GETARG_INT64(1);
597 598 599 600
	RangeVar   *sequence;

	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
																"setval"));
601

602
	do_setval(sequence, next, true);
603

604
	PG_RETURN_INT64(next);
605 606
}

607 608 609 610
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
611 612 613 614
Datum
setval_and_iscalled(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
615
	int64		next = PG_GETARG_INT64(1);
616
	bool		iscalled = PG_GETARG_BOOL(2);
617
	RangeVar   *sequence;
618

619 620
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
																"setval"));
621

622
	do_setval(sequence, next, iscalled);
623

624
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
625 626
}

627

628 629 630 631 632 633 634
/*
 * Given a relation name, open and lock the sequence.  p_elm and p_rel are
 * output parameters.
 */
static void
init_sequence(const char *caller, RangeVar *relation,
			  SeqTable *p_elm, Relation *p_rel)
635
{
636
	Oid			relid = RangeVarGetRelid(relation, false);
637 638
	TransactionId thisxid = GetCurrentTransactionId();
	SeqTable	elm;
639
	Relation	seqrel;
640 641
	
	/* Look to see if we already have a seqtable entry for relation */
642
	for (elm = seqtab; elm != NULL; elm = elm->next)
643
	{
644
		if (elm->relid == relid)
645 646 647
			break;
	}

648 649 650 651 652 653 654 655
	/*
	 * Open the sequence relation, acquiring AccessShareLock if we don't
	 * already have a lock in the current xact.
	 */
	if (elm == NULL || elm->xid != thisxid)
		seqrel = relation_open(relid, AccessShareLock);
	else
		seqrel = relation_open(relid, NoLock);
656

657
	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
658 659
		elog(ERROR, "%s.%s: %s is not a sequence",
			 relation->relname, caller, relation->relname);
660

661
	/*
662
	 * Allocate new seqtable entry if we didn't find one.
663 664 665 666 667
	 *
	 * 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.
	 */ 
668
	if (elm == NULL)
669
	{
670 671
		/*
		 * Time to make a new seqtable entry.  These entries live as long
672 673 674
		 * as the backend does, so we use plain malloc for them.
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
675 676
		if (elm == NULL)
			elog(ERROR, "Memory exhausted in init_sequence");
677
		elm->relid = relid;
678 679 680 681
		/* increment is set to 0 until we do read_info (see currval) */
		elm->last = elm->cached = elm->increment = 0;
		elm->next = seqtab;
		seqtab = elm;
682 683
	}

684 685 686 687 688
	/* Flag that we have a lock in the current xact. */
	elm->xid = thisxid;

	*p_elm = elm;
	*p_rel = seqrel;
689 690 691
}


692 693 694 695
/* Given an opened relation, lock the page buffer and find the tuple */
static Form_pg_sequence
read_info(const char *caller, SeqTable elm,
		  Relation rel, Buffer *buf)
696
{
697 698 699 700 701
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
	sequence_magic *sm;
	Form_pg_sequence seq;
702

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
	if (rel->rd_nblocks > 1)
		elog(ERROR, "%s.%s: invalid number of blocks in sequence",
			 RelationGetRelationName(rel), caller);

	*buf = ReadBuffer(rel, 0);
	if (!BufferIsValid(*buf))
		elog(ERROR, "%s.%s: ReadBuffer failed",
			 RelationGetRelationName(rel), caller);

	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);

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

	if (sm->magic != SEQ_MAGIC)
		elog(ERROR, "%s.%s: bad magic (%08X)",
			 RelationGetRelationName(rel), caller, sm->magic);

	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;
730 731 732
}


733
static void
734
init_params(CreateSeqStmt *seq, Form_pg_sequence new)
735
{
736 737 738 739 740 741
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
	List	   *option;
742

743
	new->is_cycled = false;
744 745
	foreach(option, seq->options)
	{
746
		DefElem    *defel = (DefElem *) lfirst(option);
747

748
		if (strcmp(defel->defname, "increment") == 0)
749
			increment_by = defel;
750
		else if (strcmp(defel->defname, "start") == 0)
751
			last_value = defel;
752
		else if (strcmp(defel->defname, "maxvalue") == 0)
753
			max_value = defel;
754
		else if (strcmp(defel->defname, "minvalue") == 0)
755
			min_value = defel;
756
		else if (strcmp(defel->defname, "cache") == 0)
757
			cache_value = defel;
758
		else if (strcmp(defel->defname, "cycle") == 0)
759 760
		{
			if (defel->arg != (Node *) NULL)
761
				elog(ERROR, "DefineSequence: CYCLE ??");
762
			new->is_cycled = true;
763 764
		}
		else
765
			elog(ERROR, "DefineSequence: option \"%s\" not recognized",
766 767 768 769 770
				 defel->defname);
	}

	if (increment_by == (DefElem *) NULL)		/* INCREMENT BY */
		new->increment_by = 1;
771
	else if ((new->increment_by = defGetInt64(increment_by)) == 0)
772
		elog(ERROR, "DefineSequence: can't INCREMENT by 0");
773 774

	if (max_value == (DefElem *) NULL)	/* MAXVALUE */
775
	{
776 777 778
		if (new->increment_by > 0)
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
		else
779
			new->max_value = -1;	/* descending seq */
780
	}
781
	else
782
		new->max_value = defGetInt64(max_value);
783

784
	if (min_value == (DefElem *) NULL)	/* MINVALUE */
785
	{
786 787 788 789
		if (new->increment_by > 0)
			new->min_value = 1; /* ascending seq */
		else
			new->min_value = SEQ_MINVALUE;		/* descending seq */
790
	}
791
	else
792
		new->min_value = defGetInt64(min_value);
793 794

	if (new->min_value >= new->max_value)
795
		elog(ERROR, "DefineSequence: MINVALUE (" INT64_FORMAT ") can't be >= MAXVALUE (" INT64_FORMAT ")",
796 797 798
			 new->min_value, new->max_value);

	if (last_value == (DefElem *) NULL) /* START WITH */
799
	{
800 801 802 803
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
804
	}
805
	else
806
		new->last_value = defGetInt64(last_value);
807 808

	if (new->last_value < new->min_value)
809
		elog(ERROR, "DefineSequence: START value (" INT64_FORMAT ") can't be < MINVALUE (" INT64_FORMAT ")",
810 811
			 new->last_value, new->min_value);
	if (new->last_value > new->max_value)
812
		elog(ERROR, "DefineSequence: START value (" INT64_FORMAT ") can't be > MAXVALUE (" INT64_FORMAT ")",
813 814 815 816
			 new->last_value, new->max_value);

	if (cache_value == (DefElem *) NULL)		/* CACHE */
		new->cache_value = 1;
817
	else if ((new->cache_value = defGetInt64(cache_value)) <= 0)
818
		elog(ERROR, "DefineSequence: CACHE (" INT64_FORMAT ") can't be <= 0",
819
			 new->cache_value);
820 821 822

}

V
Vadim B. Mikheev 已提交
823

B
Bruce Momjian 已提交
824 825
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
826
{
B
Bruce Momjian 已提交
827 828 829 830 831 832 833
	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);
834
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
835

836
	if (info != XLOG_SEQ_LOG)
837
		elog(PANIC, "seq_redo: unknown op code %u", info);
V
Vadim B. Mikheev 已提交
838 839 840 841 842

	reln = XLogOpenRelation(true, RM_SEQ_ID, xlrec->node);
	if (!RelationIsValid(reln))
		return;

843
	buffer = XLogReadBuffer(true, reln, 0);
V
Vadim B. Mikheev 已提交
844
	if (!BufferIsValid(buffer))
845
		elog(PANIC, "seq_redo: can't read block of %u/%u",
B
Bruce Momjian 已提交
846
			 xlrec->node.tblNode, xlrec->node.relNode);
V
Vadim B. Mikheev 已提交
847 848 849

	page = (Page) BufferGetPage(buffer);

850 851
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
852 853 854
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
855

B
Bruce Momjian 已提交
856
	item = (char *) xlrec + sizeof(xl_seq_rec);
857 858
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
859
	if (PageAddItem(page, (Item) item, itemsz,
860
					FirstOffsetNumber, LP_USED) == InvalidOffsetNumber)
861
		elog(PANIC, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
862 863 864 865 866 867

	PageSetLSN(page, lsn);
	PageSetSUI(page, ThisStartUpID);
	UnlockAndWriteBuffer(buffer);
}

B
Bruce Momjian 已提交
868 869
void
seq_undo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
870 871 872
{
}

B
Bruce Momjian 已提交
873 874
void
seq_desc(char *buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
875
{
B
Bruce Momjian 已提交
876 877
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
878 879 880 881 882 883 884 885 886

	if (info == XLOG_SEQ_LOG)
		strcat(buf, "log: ");
	else
	{
		strcat(buf, "UNKNOWN");
		return;
	}

887
	sprintf(buf + strlen(buf), "node %u/%u",
B
Bruce Momjian 已提交
888
			xlrec->node.tblNode, xlrec->node.relNode);
V
Vadim B. Mikheev 已提交
889
}