sequence.c 23.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5
 *
6
 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 8 9 10
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
11
 *	  $Header: /cvsroot/pgsql/src/backend/commands/sequence.c,v 1.78 2002/05/21 22:05:54 tgl 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/tablecmds.h"
21
#include "commands/sequence.h"
B
Bruce Momjian 已提交
22
#include "miscadmin.h"
23
#include "utils/acl.h"
B
Bruce Momjian 已提交
24
#include "utils/builtins.h"
25
#include "utils/int8.h"
26

27

28
#define SEQ_MAGIC	  0x1717
29

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

#define SEQ_MINVALUE	(-SEQ_MAXVALUE)
41

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

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

54 55
typedef struct SeqTableData
{
56
	Oid			relid;
57 58 59 60
	Relation	rel;			/* NULL if rel is not open in cur xact */
	int64		cached;
	int64		last;
	int64		increment;
61
	struct SeqTableData *next;
62
} SeqTableData;
63 64 65 66 67

typedef SeqTableData *SeqTable;

static SeqTable seqtab = NULL;

68
static SeqTable init_sequence(char *caller, RangeVar *relation);
69 70
static Form_pg_sequence read_info(char *caller, SeqTable elm, Buffer *buf);
static void init_params(CreateSeqStmt *seq, Form_pg_sequence new);
71
static int64 get_param(DefElem *def);
72
static void do_setval(RangeVar *sequence, int64 next, bool iscalled);
73 74

/*
B
Bruce Momjian 已提交
75
 * DefineSequence
76
 *				Creates a new sequence relation
77 78
 */
void
79
DefineSequence(CreateSeqStmt *seq)
80
{
81
	FormData_pg_sequence new;
82
	CreateStmt *stmt = makeNode(CreateStmt);
83
	Oid			seqoid;
84 85 86
	Relation	rel;
	Buffer		buf;
	PageHeader	page;
87
	sequence_magic *sm;
88 89 90 91 92
	HeapTuple	tuple;
	TupleDesc	tupDesc;
	Datum		value[SEQ_COL_LASTCOL];
	char		null[SEQ_COL_LASTCOL];
	int			i;
93
	NameData	name;
94 95 96 97 98

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

	/*
99
	 * Create relation (and fill *null & *value)
100 101 102
	 */
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
103
	{
104 105 106
		ColumnDef  *coldef;
		TypeName   *typnam;

107 108
		typnam = makeNode(TypeName);
		typnam->setof = FALSE;
109
		typnam->arrayBounds = NIL;
B
Bruce Momjian 已提交
110
		typnam->typmod = -1;
111 112
		coldef = makeNode(ColumnDef);
		coldef->typename = typnam;
113 114
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
115 116 117 118 119
		coldef->is_not_null = false;
		null[i - 1] = ' ';

		switch (i)
		{
120
			case SEQ_COL_NAME:
121
				typnam->typeid = NAMEOID;
122
				coldef->colname = "sequence_name";
123
				namestrcpy(&name, seq->sequence->relname);
124
				value[i - 1] = NameGetDatum(&name);
125 126
				break;
			case SEQ_COL_LASTVAL:
127
				typnam->typeid = INT8OID;
128
				coldef->colname = "last_value";
129
				value[i - 1] = Int64GetDatumFast(new.last_value);
130 131
				break;
			case SEQ_COL_INCBY:
132
				typnam->typeid = INT8OID;
133
				coldef->colname = "increment_by";
134
				value[i - 1] = Int64GetDatumFast(new.increment_by);
135 136
				break;
			case SEQ_COL_MAXVALUE:
137
				typnam->typeid = INT8OID;
138
				coldef->colname = "max_value";
139
				value[i - 1] = Int64GetDatumFast(new.max_value);
140 141
				break;
			case SEQ_COL_MINVALUE:
142
				typnam->typeid = INT8OID;
143
				coldef->colname = "min_value";
144
				value[i - 1] = Int64GetDatumFast(new.min_value);
145 146
				break;
			case SEQ_COL_CACHE:
147
				typnam->typeid = INT8OID;
148
				coldef->colname = "cache_value";
149
				value[i - 1] = Int64GetDatumFast(new.cache_value);
150
				break;
V
Vadim B. Mikheev 已提交
151
			case SEQ_COL_LOG:
152
				typnam->typeid = INT8OID;
V
Vadim B. Mikheev 已提交
153
				coldef->colname = "log_cnt";
154
				value[i - 1] = Int64GetDatum((int64) 1);
V
Vadim B. Mikheev 已提交
155
				break;
156
			case SEQ_COL_CYCLE:
157
				typnam->typeid = BOOLOID;
158
				coldef->colname = "is_cycled";
159
				value[i - 1] = BoolGetDatum(new.is_cycled);
160 161
				break;
			case SEQ_COL_CALLED:
162
				typnam->typeid = BOOLOID;
163
				coldef->colname = "is_called";
164
				value[i - 1] = BoolGetDatum(false);
165
				break;
166 167 168 169
		}
		stmt->tableElts = lappend(stmt->tableElts, coldef);
	}

170 171
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
172
	stmt->constraints = NIL;
173
	stmt->hasoids = false;
174

175
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
176

177
	rel = heap_open(seqoid, AccessExclusiveLock);
178
	tupDesc = RelationGetDescr(rel);
179

180 181
	/* Initialize first page of relation with special magic number */

182 183 184
	buf = ReadBuffer(rel, P_NEW);

	if (!BufferIsValid(buf))
185
		elog(ERROR, "DefineSequence: ReadBuffer failed");
186

187 188
	Assert(BufferGetBlockNumber(buf) == 0);

189 190 191 192 193 194
	page = (PageHeader) BufferGetPage(buf);

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

195 196 197
	/* hack: ensure heap_insert will insert on the just-created page */
	rel->rd_targblock = 0;

198
	/* Now form & insert sequence tuple */
199
	tuple = heap_formtuple(tupDesc, value, null);
200
	simple_heap_insert(rel, tuple);
201

202 203
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

204
	/*
205 206 207 208 209 210 211 212 213 214 215 216 217
	 * 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 :-(
218
	 */
219
	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
220
	START_CRIT_SECTION();
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

	{
		/*
		 * 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);

		((HeapTupleHeader) item)->t_xmin = FrozenTransactionId;
		((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;

		tuple->t_data->t_xmin = FrozenTransactionId;
		tuple->t_data->t_infomask |= HEAP_XMIN_COMMITTED;
	}

243
	{
244 245 246 247
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];
		Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
248 249

		/* We do not log first nextval call, so "advance" sequence here */
250
		/* Note we are scribbling on local tuple, not the disk buffer */
251
		newseq->is_called = true;
252 253 254 255 256 257 258 259 260
		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;
261
		rdata[1].data = (char *) tuple->t_data;
262 263 264 265 266 267 268 269 270
		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();
271

272
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);
273 274
	WriteBuffer(buf);
	heap_close(rel, NoLock);
275 276 277
}


278 279
Datum
nextval(PG_FUNCTION_ARGS)
280
{
281
	text	   *seqin = PG_GETARG_TEXT_P(0);
282
	RangeVar   *sequence;
283 284
	SeqTable	elm;
	Buffer		buf;
285
	Page		page;
286
	Form_pg_sequence seq;
287
	int64		incby,
288 289
				maxv,
				minv,
V
Vadim B. Mikheev 已提交
290 291 292 293
				cache,
				log,
				fetch,
				last;
294
	int64		result,
295 296
				next,
				rescnt = 0;
V
Vadim B. Mikheev 已提交
297
	bool		logit = false;
298

299 300 301
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
																"nextval"));

V
Vadim B. Mikheev 已提交
302
	/* open and AccessShareLock sequence */
303
	elm = init_sequence("nextval", sequence);
304

305 306
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
		elog(ERROR, "%s.nextval: you don't have permissions to set sequence %s",
307
			 sequence->relname, sequence->relname);
308 309 310 311

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
		elm->last += elm->increment;
312
		PG_RETURN_INT64(elm->last);
313
	}
314

B
Bruce Momjian 已提交
315 316
	seq = read_info("nextval", elm, &buf);		/* lock page' buffer and
												 * read tuple */
317
	page = BufferGetPage(buf);
318

V
Vadim B. Mikheev 已提交
319
	last = next = result = seq->last_value;
320 321 322
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
323 324
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
325

326
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
327
	{
328
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
329 330 331
		fetch--;
		log--;
	}
332

333 334 335 336 337 338 339 340 341 342
	/*
	 * 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 已提交
343 344
	if (log < fetch)
	{
345 346
		/* forced log to satisfy local demand for values */
		fetch = log = fetch + SEQ_LOG_VALS;
V
Vadim B. Mikheev 已提交
347 348
		logit = true;
	}
349 350 351 352 353 354 355 356 357 358 359
	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 已提交
360

B
Bruce Momjian 已提交
361
	while (fetch)				/* try to fetch cache [+ log ] numbers */
362
	{
363 364 365 366
		/*
		 * Check MAXVALUE for ascending sequences and MINVALUE for
		 * descending sequences
		 */
367
		if (incby > 0)
368
		{
369
			/* ascending sequence */
370 371 372 373
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
374
					break;		/* stop fetching */
375 376
				if (!seq->is_cycled)
					elog(ERROR, "%s.nextval: reached MAXVALUE (" INT64_FORMAT ")",
377
						 sequence->relname, maxv);
378 379 380 381 382 383 384
				next = minv;
			}
			else
				next += incby;
		}
		else
		{
385
			/* descending sequence */
386 387 388 389
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
390
					break;		/* stop fetching */
391 392
				if (!seq->is_cycled)
					elog(ERROR, "%s.nextval: reached MINVALUE (" INT64_FORMAT ")",
393
						 sequence->relname, minv);
394 395 396 397 398
				next = maxv;
			}
			else
				next += incby;
		}
V
Vadim B. Mikheev 已提交
399 400 401 402 403 404
		fetch--;
		if (rescnt < cache)
		{
			log--;
			rescnt++;
			last = next;
B
Bruce Momjian 已提交
405 406
			if (rescnt == 1)	/* if it's first result - */
				result = next;	/* it's what to return */
V
Vadim B. Mikheev 已提交
407
		}
408 409
	}

410 411 412
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

413 414
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
415 416
	elm->cached = last;			/* last fetched number */

417
	START_CRIT_SECTION();
V
Vadim B. Mikheev 已提交
418 419 420 421
	if (logit)
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
422
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
423 424

		xlrec.node = elm->rel->rd_node;
425
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
426
		rdata[0].data = (char *) &xlrec;
427 428 429 430
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

		seq->last_value = next;
431
		seq->is_called = true;
432 433
		seq->log_cnt = 0;
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
434 435 436
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
437 438
		rdata[1].next = NULL;

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

441 442
		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
443
	}
444

445
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
446
	seq->last_value = last;		/* last fetched number */
447
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
448
	seq->log_cnt = log;			/* how much is logged */
449
	END_CRIT_SECTION();
450

V
Vadim B. Mikheev 已提交
451 452
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

453
	if (WriteBuffer(buf) == STATUS_ERROR)
454
		elog(ERROR, "%s.nextval: WriteBuffer failed", sequence->relname);
455

456
	PG_RETURN_INT64(result);
457 458
}

459 460
Datum
currval(PG_FUNCTION_ARGS)
461
{
462
	text	   *seqin = PG_GETARG_TEXT_P(0);
463
	RangeVar   *sequence;
464
	SeqTable	elm;
465
	int64		result;
466

467 468 469
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
																"currval"));

V
Vadim B. Mikheev 已提交
470
	/* open and AccessShareLock sequence */
471
	elm = init_sequence("currval", sequence);
472

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

477
	if (elm->increment == 0)	/* nextval/read_info were not called */
478
		elog(ERROR, "%s.currval is not yet defined in this session",
479
			 sequence->relname);
480 481 482

	result = elm->last;

483
	PG_RETURN_INT64(result);
484 485
}

B
Bruce Momjian 已提交
486
/*
487 488 489 490
 * 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 已提交
491
 * work if multiple users are attached to the database and referencing
492 493
 * the sequence (unlikely if pg_dump is restoring it).
 *
B
Bruce Momjian 已提交
494
 * It is necessary to have the 3 arg version so that pg_dump can
495 496 497 498
 * 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 已提交
499
static void
500
do_setval(RangeVar *sequence, int64 next, bool iscalled)
M
 
Marc G. Fournier 已提交
501 502
{
	SeqTable	elm;
503
	Buffer		buf;
504
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
505

506
	/* open and AccessShareLock sequence */
507
	elm = init_sequence("setval", sequence);
508 509

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

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

516
	if ((next < seq->min_value) || (next > seq->max_value))
517
		elog(ERROR, "%s.setval: value " INT64_FORMAT " is out of bounds (" INT64_FORMAT "," INT64_FORMAT ")",
518
			 sequence->relname, next, seq->min_value, seq->max_value);
M
 
Marc G. Fournier 已提交
519 520 521

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

525
	START_CRIT_SECTION();
V
Vadim B. Mikheev 已提交
526 527 528
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
529
		XLogRecData rdata[2];
530
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
531 532

		xlrec.node = elm->rel->rd_node;
533
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
534
		rdata[0].data = (char *) &xlrec;
535 536 537 538
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

		seq->last_value = next;
539
		seq->is_called = true;
540 541
		seq->log_cnt = 0;
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
542 543 544
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
545 546
		rdata[1].next = NULL;

B
Bruce Momjian 已提交
547
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);
548 549 550

		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
551
	}
552 553
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
554
	seq->is_called = iscalled;
555
	seq->log_cnt = (iscalled) ? 0 : 1;
556
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
557

V
Vadim B. Mikheev 已提交
558 559
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

560
	if (WriteBuffer(buf) == STATUS_ERROR)
561
		elog(ERROR, "%s.setval: WriteBuffer failed", sequence->relname);
562 563
}

564 565 566 567
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
568 569 570 571
Datum
setval(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
572
	int64		next = PG_GETARG_INT64(1);
573 574 575 576
	RangeVar   *sequence;

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

578
	do_setval(sequence, next, true);
579

580
	PG_RETURN_INT64(next);
581 582
}

583 584 585 586
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
587 588 589 590
Datum
setval_and_iscalled(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
591
	int64		next = PG_GETARG_INT64(1);
592
	bool		iscalled = PG_GETARG_BOOL(2);
593
	RangeVar   *sequence;
594

595 596
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
																"setval"));
597

598
	do_setval(sequence, next, iscalled);
599

600
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
601 602
}

603
static Form_pg_sequence
B
Bruce Momjian 已提交
604
read_info(char *caller, SeqTable elm, Buffer *buf)
605
{
B
Bruce Momjian 已提交
606 607 608
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
609
	sequence_magic *sm;
B
Bruce Momjian 已提交
610
	Form_pg_sequence seq;
611

612
	if (elm->rel->rd_nblocks > 1)
613
		elog(ERROR, "%s.%s: invalid number of blocks in sequence",
614
			 RelationGetRelationName(elm->rel), caller);
615 616 617

	*buf = ReadBuffer(elm->rel, 0);
	if (!BufferIsValid(*buf))
618 619
		elog(ERROR, "%s.%s: ReadBuffer failed",
			 RelationGetRelationName(elm->rel), caller);
620

V
Vadim B. Mikheev 已提交
621 622
	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);

623 624 625 626
	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

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

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

634
	seq = (Form_pg_sequence) GETSTRUCT(&tuple);
635 636 637

	elm->increment = seq->increment_by;

638
	return seq;
639 640 641
}


642
static SeqTable
643
init_sequence(char *caller, RangeVar *relation)
644
{
645
	Oid			relid = RangeVarGetRelid(relation, false);
646
	SeqTable	elm,
647 648
				prev = (SeqTable) NULL;
	Relation	seqrel;
649 650
	
	/* Look to see if we already have a seqtable entry for relation */
651
	for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next)
652
	{
653
		if (elm->relid == relid)
654
			break;
655
		prev = elm;
656 657
	}

658 659 660
	/* If so, and if it's already been opened in this xact, just return it */
	if (elm != (SeqTable) NULL && elm->rel != (Relation) NULL)
		return elm;
661

662
	/* Else open and check it */
663
	seqrel = heap_open(relid, AccessShareLock);
664
	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
665 666
		elog(ERROR, "%s.%s: %s is not a sequence",
			 relation->relname, caller, relation->relname);
667

668 669 670 671 672 673 674 675
	/*
	 * If elm exists but elm->rel is NULL, the seqtable entry is left over
	 * from a previous xact -- update the entry and reuse it.
	 *
	 * 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.
	 */ 
676 677 678
	if (elm != (SeqTable) NULL)
	{
		elm->rel = seqrel;
679 680 681
	}
	else
	{
682 683
		/*
		 * Time to make a new seqtable entry.  These entries live as long
684 685 686
		 * as the backend does, so we use plain malloc for them.
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
687 688
		if (elm == NULL)
			elog(ERROR, "Memory exhausted in init_sequence");
689
		elm->rel = seqrel;
690
		elm->relid = relid;
691 692 693
		elm->cached = elm->last = elm->increment = 0;
		elm->next = (SeqTable) NULL;

694 695 696
		if (seqtab == (SeqTable) NULL)
			seqtab = elm;
		else
697
			prev->next = elm;
698 699
	}

700
	return elm;
701 702 703 704
}


/*
B
Bruce Momjian 已提交
705
 * CloseSequences
706
 *				is called by xact mgr at commit/abort.
707 708
 */
void
709
CloseSequences(void)
710
{
711 712
	SeqTable	elm;
	Relation	rel;
713

714
	for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next)
715
	{
716
		rel = elm->rel;
717
		if (rel != (Relation) NULL)		/* opened in current xact */
718 719
		{
			elm->rel = (Relation) NULL;
720
			heap_close(rel, AccessShareLock);
721 722
		}
	}
723 724 725
}


726
static void
727
init_params(CreateSeqStmt *seq, Form_pg_sequence new)
728
{
729 730 731 732 733 734
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
	List	   *option;
735

736
	new->is_cycled = false;
737 738
	foreach(option, seq->options)
	{
739
		DefElem    *defel = (DefElem *) lfirst(option);
740

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

	if (increment_by == (DefElem *) NULL)		/* INCREMENT BY */
		new->increment_by = 1;
	else if ((new->increment_by = get_param(increment_by)) == 0)
765
		elog(ERROR, "DefineSequence: can't INCREMENT by 0");
766 767

	if (max_value == (DefElem *) NULL)	/* MAXVALUE */
768
	{
769 770 771
		if (new->increment_by > 0)
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
		else
772
			new->max_value = -1;	/* descending seq */
773
	}
774
	else
775
		new->max_value = get_param(max_value);
776

777
	if (min_value == (DefElem *) NULL)	/* MINVALUE */
778
	{
779 780 781 782
		if (new->increment_by > 0)
			new->min_value = 1; /* ascending seq */
		else
			new->min_value = SEQ_MINVALUE;		/* descending seq */
783
	}
784
	else
785 786 787
		new->min_value = get_param(min_value);

	if (new->min_value >= new->max_value)
788
		elog(ERROR, "DefineSequence: MINVALUE (" INT64_FORMAT ") can't be >= MAXVALUE (" INT64_FORMAT ")",
789 790 791
			 new->min_value, new->max_value);

	if (last_value == (DefElem *) NULL) /* START WITH */
792
	{
793 794 795 796
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
797
	}
798
	else
799 800 801
		new->last_value = get_param(last_value);

	if (new->last_value < new->min_value)
802
		elog(ERROR, "DefineSequence: START value (" INT64_FORMAT ") can't be < MINVALUE (" INT64_FORMAT ")",
803 804
			 new->last_value, new->min_value);
	if (new->last_value > new->max_value)
805
		elog(ERROR, "DefineSequence: START value (" INT64_FORMAT ") can't be > MAXVALUE (" INT64_FORMAT ")",
806 807 808 809 810
			 new->last_value, new->max_value);

	if (cache_value == (DefElem *) NULL)		/* CACHE */
		new->cache_value = 1;
	else if ((new->cache_value = get_param(cache_value)) <= 0)
811
		elog(ERROR, "DefineSequence: CACHE (" INT64_FORMAT ") can't be <= 0",
812
			 new->cache_value);
813 814 815

}

816
static int64
817
get_param(DefElem *def)
818
{
819
	if (def->arg == (Node *) NULL)
820
		elog(ERROR, "DefineSequence: \"%s\" value unspecified", def->defname);
821

822 823
	if (IsA(def->arg, Integer))
		return (int64) intVal(def->arg);
824

825
	/*
826 827
	 * Values too large for int4 will be represented as Float constants by
	 * the lexer.  Accept these if they are valid int8 strings.
828 829 830
	 */
	if (IsA(def->arg, Float))
		return DatumGetInt64(DirectFunctionCall1(int8in,
831
									 CStringGetDatum(strVal(def->arg))));
832 833

	/* Shouldn't get here unless parser messed up */
834
	elog(ERROR, "DefineSequence: \"%s\" value must be integer", def->defname);
835
	return 0;					/* not reached; keep compiler quiet */
836
}
V
Vadim B. Mikheev 已提交
837

B
Bruce Momjian 已提交
838 839
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
840
{
B
Bruce Momjian 已提交
841 842 843 844 845 846 847
	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);
848
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
849

850
	if (info != XLOG_SEQ_LOG)
851
		elog(PANIC, "seq_redo: unknown op code %u", info);
V
Vadim B. Mikheev 已提交
852 853 854 855 856

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

857
	buffer = XLogReadBuffer(true, reln, 0);
V
Vadim B. Mikheev 已提交
858
	if (!BufferIsValid(buffer))
859
		elog(PANIC, "seq_redo: can't read block of %u/%u",
B
Bruce Momjian 已提交
860
			 xlrec->node.tblNode, xlrec->node.relNode);
V
Vadim B. Mikheev 已提交
861 862 863

	page = (Page) BufferGetPage(buffer);

864 865
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
866 867 868
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
869

B
Bruce Momjian 已提交
870
	item = (char *) xlrec + sizeof(xl_seq_rec);
871 872
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
873
	if (PageAddItem(page, (Item) item, itemsz,
874
					FirstOffsetNumber, LP_USED) == InvalidOffsetNumber)
875
		elog(PANIC, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
876 877 878 879 880 881

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

B
Bruce Momjian 已提交
882 883
void
seq_undo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
884 885 886
{
}

B
Bruce Momjian 已提交
887 888
void
seq_desc(char *buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
889
{
B
Bruce Momjian 已提交
890 891
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
892 893 894 895 896 897 898 899 900

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

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