sequence.c 24.4 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
11
 *	  $Header: /cvsroot/pgsql/src/backend/commands/sequence.c,v 1.89 2002/11/10 00:10:20 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
/*
 * We store a SeqTable item for every sequence we have touched in the current
 * session.  This is needed to hold onto nextval/currval state.  (We can't
 * rely on the relcache, since it's only, well, a cache, and may decide to
 * discard entries.)
 *
B
Bruce Momjian 已提交
63
 * XXX We use linear search to find pre-existing SeqTable entries.	This is
64 65 66
 * good when only a small number of sequences are touched in a session, but
 * would suck with many different sequences.  Perhaps use a hashtable someday.
 */
67 68
typedef struct SeqTableData
{
69 70 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

static void init_sequence(const char *caller, RangeVar *relation,
B
Bruce Momjian 已提交
84
			  SeqTable *p_elm, Relation *p_rel);
85
static Form_pg_sequence read_info(const char *caller, SeqTable elm,
B
Bruce Momjian 已提交
86
		  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 129
		coldef = makeNode(ColumnDef);
		coldef->typename = typnam;
130 131
		coldef->inhcount = 0;
		coldef->is_local = true;
132
		coldef->is_not_null = true;
133 134
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
135 136 137
		coldef->constraints = NIL;
		coldef->support = NULL;

138 139 140 141
		null[i - 1] = ' ';

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

192 193
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
194
	stmt->constraints = NIL;
195
	stmt->hasoids = false;
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 205 206
	buf = ReadBuffer(rel, P_NEW);

	if (!BufferIsValid(buf))
207
		elog(ERROR, "DefineSequence: ReadBuffer failed");
208

209 210
	Assert(BufferGetBlockNumber(buf) == 0);

211 212 213 214 215 216
	page = (PageHeader) BufferGetPage(buf);

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

217 218 219
	/* hack: ensure heap_insert will insert on the just-created page */
	rel->rd_targblock = 0;

220
	/* Now form & insert sequence tuple */
221
	tuple = heap_formtuple(tupDesc, value, null);
222
	simple_heap_insert(rel, tuple);
223

224 225
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

226
	/*
227 228 229
	 * Two special hacks here:
	 *
	 * 1. Since VACUUM does not process sequences, we have to force the tuple
B
Bruce Momjian 已提交
230 231
	 * to have xmin = FrozenTransactionId now.	Otherwise it would become
	 * invisible to SELECTs after 2G transactions.	It is okay to do this
232 233 234 235 236 237
	 * 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
B
Bruce Momjian 已提交
238
	 * would re-init page and sequence magic number would be lost.	This
239
	 * means two log records instead of one :-(
240
	 */
241
	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
242

243
	START_CRIT_SECTION();
244 245 246

	{
		/*
B
Bruce Momjian 已提交
247 248 249 250 251 252
		 * 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.
253 254 255 256 257 258 259
		 */
		ItemId		itemId;
		Item		item;

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

260
		HeapTupleHeaderSetXmin((HeapTupleHeader) item, FrozenTransactionId);
261 262
		((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;

263
		HeapTupleHeaderSetXmin(tuple->t_data, FrozenTransactionId);
264 265 266
		tuple->t_data->t_infomask |= HEAP_XMIN_COMMITTED;
	}

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

		/* We do not log first nextval call, so "advance" sequence here */
276
		/* Note we are scribbling on local tuple, not the disk buffer */
277
		newseq->is_called = true;
278 279 280 281 282 283 284 285 286
		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;
287
		rdata[1].data = (char *) tuple->t_data;
288 289 290 291 292 293 294 295
		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);
	}
296

297
	END_CRIT_SECTION();
298

299
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);
300 301
	WriteBuffer(buf);
	heap_close(rel, NoLock);
302 303 304
}


305 306
Datum
nextval(PG_FUNCTION_ARGS)
307
{
308
	text	   *seqin = PG_GETARG_TEXT_P(0);
309
	RangeVar   *sequence;
310
	SeqTable	elm;
311
	Relation	seqrel;
312
	Buffer		buf;
313
	Page		page;
314
	Form_pg_sequence seq;
315
	int64		incby,
316 317
				maxv,
				minv,
V
Vadim B. Mikheev 已提交
318 319 320 321
				cache,
				log,
				fetch,
				last;
322
	int64		result,
323 324
				next,
				rescnt = 0;
V
Vadim B. Mikheev 已提交
325
	bool		logit = false;
326

327
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
B
Bruce Momjian 已提交
328
															 "nextval"));
329

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

333 334
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
		elog(ERROR, "%s.nextval: you don't have permissions to set sequence %s",
335
			 sequence->relname, sequence->relname);
336 337 338 339

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
		elm->last += elm->increment;
340
		relation_close(seqrel, NoLock);
341
		PG_RETURN_INT64(elm->last);
342
	}
343

344 345
	/* lock page' buffer and read tuple */
	seq = read_info("nextval", elm, seqrel, &buf);
346
	page = BufferGetPage(buf);
347

V
Vadim B. Mikheev 已提交
348
	last = next = result = seq->last_value;
349 350 351
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
352 353
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
354

355
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
356
	{
357
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
358 359 360
		fetch--;
		log--;
	}
361

362
	/*
B
Bruce Momjian 已提交
363
	 * Decide whether we should emit a WAL log record.	If so, force up
364 365 366
	 * the fetch count to grab SEQ_LOG_VALS more values than we actually
	 * need to cache.  (These will then be usable without logging.)
	 *
B
Bruce Momjian 已提交
367 368
	 * 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
369
	 * checkpoint would fail to advance the sequence past the logged
B
Bruce Momjian 已提交
370
	 * values.	In this case we may as well fetch extra values.
371
	 */
V
Vadim B. Mikheev 已提交
372 373
	if (log < fetch)
	{
374 375
		/* forced log to satisfy local demand for values */
		fetch = log = fetch + SEQ_LOG_VALS;
V
Vadim B. Mikheev 已提交
376 377
		logit = true;
	}
378 379 380 381 382 383 384 385 386 387 388
	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 已提交
389

B
Bruce Momjian 已提交
390
	while (fetch)				/* try to fetch cache [+ log ] numbers */
391
	{
392 393 394 395
		/*
		 * Check MAXVALUE for ascending sequences and MINVALUE for
		 * descending sequences
		 */
396
		if (incby > 0)
397
		{
398
			/* ascending sequence */
399 400 401 402
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
403
					break;		/* stop fetching */
404
				if (!seq->is_cycled)
405
				{
B
Bruce Momjian 已提交
406 407
					char		buf[100];

408 409 410 411
					snprintf(buf, 100, INT64_FORMAT, maxv);
					elog(ERROR, "%s.nextval: reached MAXVALUE (%s)",
						 sequence->relname, buf);
				}
412 413 414 415 416 417 418
				next = minv;
			}
			else
				next += incby;
		}
		else
		{
419
			/* descending sequence */
420 421 422 423
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
424
					break;		/* stop fetching */
425
				if (!seq->is_cycled)
426
				{
B
Bruce Momjian 已提交
427 428
					char		buf[100];

429 430 431 432
					snprintf(buf, 100, INT64_FORMAT, minv);
					elog(ERROR, "%s.nextval: reached MINVALUE (%s)",
						 sequence->relname, buf);
				}
433 434 435 436 437
				next = maxv;
			}
			else
				next += incby;
		}
V
Vadim B. Mikheev 已提交
438 439 440 441 442 443
		fetch--;
		if (rescnt < cache)
		{
			log--;
			rescnt++;
			last = next;
B
Bruce Momjian 已提交
444 445
			if (rescnt == 1)	/* if it's first result - */
				result = next;	/* it's what to return */
V
Vadim B. Mikheev 已提交
446
		}
447 448
	}

449 450 451
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

452 453
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
454 455
	elm->cached = last;			/* last fetched number */

456
	START_CRIT_SECTION();
457 458 459

	/* XLOG stuff */
	if (logit && !seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
460 461 462
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
463
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
464

465
		xlrec.node = seqrel->rd_node;
466
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
467
		rdata[0].data = (char *) &xlrec;
468 469 470
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

471
		/* set values that will be saved in xlog */
472
		seq->last_value = next;
473
		seq->is_called = true;
474
		seq->log_cnt = 0;
475

476
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
477 478 479
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
480 481
		rdata[1].next = NULL;

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

484 485
		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
486
	}
487

488
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
489
	seq->last_value = last;		/* last fetched number */
490
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
491
	seq->log_cnt = log;			/* how much is logged */
492

493
	END_CRIT_SECTION();
494

V
Vadim B. Mikheev 已提交
495 496
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

B
Bruce Momjian 已提交
497
	WriteBuffer(buf);
498

499 500
	relation_close(seqrel, NoLock);

501
	PG_RETURN_INT64(result);
502 503
}

504 505
Datum
currval(PG_FUNCTION_ARGS)
506
{
507
	text	   *seqin = PG_GETARG_TEXT_P(0);
508
	RangeVar   *sequence;
509
	SeqTable	elm;
510
	Relation	seqrel;
511
	int64		result;
512

513
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
B
Bruce Momjian 已提交
514
															 "currval"));
515

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

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

523
	if (elm->increment == 0)	/* nextval/read_info were not called */
524
		elog(ERROR, "%s.currval is not yet defined in this session",
525
			 sequence->relname);
526 527 528

	result = elm->last;

529 530
	relation_close(seqrel, NoLock);

531
	PG_RETURN_INT64(result);
532 533
}

B
Bruce Momjian 已提交
534
/*
535 536 537 538
 * 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 已提交
539
 * work if multiple users are attached to the database and referencing
540 541
 * the sequence (unlikely if pg_dump is restoring it).
 *
B
Bruce Momjian 已提交
542
 * It is necessary to have the 3 arg version so that pg_dump can
543 544 545 546
 * 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 已提交
547
static void
548
do_setval(RangeVar *sequence, int64 next, bool iscalled)
M
 
Marc G. Fournier 已提交
549 550
{
	SeqTable	elm;
551
	Relation	seqrel;
552
	Buffer		buf;
553
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
554

555
	/* open and AccessShareLock sequence */
556
	init_sequence("setval", sequence, &elm, &seqrel);
557 558

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

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

565
	if ((next < seq->min_value) || (next > seq->max_value))
566
	{
B
Bruce Momjian 已提交
567 568 569 570
		char		bufv[100],
					bufm[100],
					bufx[100];

571 572 573 574 575 576
		snprintf(bufv, 100, INT64_FORMAT, next);
		snprintf(bufm, 100, INT64_FORMAT, seq->min_value);
		snprintf(bufx, 100, INT64_FORMAT, seq->max_value);
		elog(ERROR, "%s.setval: value %s is out of bounds (%s,%s)",
			 sequence->relname, bufv, bufm, bufx);
	}
M
 
Marc G. Fournier 已提交
577 578 579

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

583
	START_CRIT_SECTION();
584 585 586

	/* XLOG stuff */
	if (!seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
587 588 589
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
590
		XLogRecData rdata[2];
591
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
592

593
		xlrec.node = seqrel->rd_node;
594
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
595
		rdata[0].data = (char *) &xlrec;
596 597 598
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

599
		/* set values that will be saved in xlog */
600
		seq->last_value = next;
601
		seq->is_called = true;
602
		seq->log_cnt = 0;
603

604
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
605 606 607
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
608 609
		rdata[1].next = NULL;

B
Bruce Momjian 已提交
610
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);
611 612 613

		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
614
	}
615

616 617
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
618
	seq->is_called = iscalled;
619
	seq->log_cnt = (iscalled) ? 0 : 1;
620

621
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
622

V
Vadim B. Mikheev 已提交
623 624
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

B
Bruce Momjian 已提交
625
	WriteBuffer(buf);
626 627

	relation_close(seqrel, NoLock);
628 629
}

630 631 632 633
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
634 635 636 637
Datum
setval(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
638
	int64		next = PG_GETARG_INT64(1);
639 640 641
	RangeVar   *sequence;

	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
B
Bruce Momjian 已提交
642
															  "setval"));
643

644
	do_setval(sequence, next, true);
645

646
	PG_RETURN_INT64(next);
647 648
}

649 650 651 652
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
653 654 655 656
Datum
setval_and_iscalled(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
657
	int64		next = PG_GETARG_INT64(1);
658
	bool		iscalled = PG_GETARG_BOOL(2);
659
	RangeVar   *sequence;
660

661
	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin,
B
Bruce Momjian 已提交
662
															  "setval"));
663

664
	do_setval(sequence, next, iscalled);
665

666
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
667 668
}

669

670 671 672 673 674 675 676
/*
 * 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)
677
{
678
	Oid			relid = RangeVarGetRelid(relation, false);
679 680
	TransactionId thisxid = GetCurrentTransactionId();
	SeqTable	elm;
681
	Relation	seqrel;
B
Bruce Momjian 已提交
682

683
	/* Look to see if we already have a seqtable entry for relation */
684
	for (elm = seqtab; elm != NULL; elm = elm->next)
685
	{
686
		if (elm->relid == relid)
687 688 689
			break;
	}

690 691 692 693 694 695 696 697
	/*
	 * 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);
698

699
	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
700 701
		elog(ERROR, "%s.%s: %s is not a sequence",
			 relation->relname, caller, relation->relname);
702

703
	/*
704
	 * Allocate new seqtable entry if we didn't find one.
705 706
	 *
	 * NOTE: seqtable entries remain in the list for the life of a backend.
B
Bruce Momjian 已提交
707 708 709
	 * If the sequence itself is deleted then the entry becomes wasted
	 * memory, but it's small enough that this should not matter.
	 */
710
	if (elm == NULL)
711
	{
712 713
		/*
		 * Time to make a new seqtable entry.  These entries live as long
714 715 716
		 * as the backend does, so we use plain malloc for them.
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
717 718
		if (elm == NULL)
			elog(ERROR, "Memory exhausted in init_sequence");
719
		elm->relid = relid;
720 721 722 723
		/* increment is set to 0 until we do read_info (see currval) */
		elm->last = elm->cached = elm->increment = 0;
		elm->next = seqtab;
		seqtab = elm;
724 725
	}

726 727 728 729 730
	/* Flag that we have a lock in the current xact. */
	elm->xid = thisxid;

	*p_elm = elm;
	*p_rel = seqrel;
731 732 733
}


734 735 736 737
/* 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)
738
{
739 740 741 742 743
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
	sequence_magic *sm;
	Form_pg_sequence seq;
744

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
	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;
772 773 774
}


775
static void
776
init_params(CreateSeqStmt *seq, Form_pg_sequence new)
777
{
778 779 780 781 782 783
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
	List	   *option;
784

785
	new->is_cycled = false;
786 787
	foreach(option, seq->options)
	{
788
		DefElem    *defel = (DefElem *) lfirst(option);
789

790
		if (strcmp(defel->defname, "increment") == 0)
791
			increment_by = defel;
792
		else if (strcmp(defel->defname, "start") == 0)
793
			last_value = defel;
794
		else if (strcmp(defel->defname, "maxvalue") == 0)
795
			max_value = defel;
796
		else if (strcmp(defel->defname, "minvalue") == 0)
797
			min_value = defel;
798
		else if (strcmp(defel->defname, "cache") == 0)
799
			cache_value = defel;
800
		else if (strcmp(defel->defname, "cycle") == 0)
801
			new->is_cycled = (defel->arg != NULL);
802
		else
803
			elog(ERROR, "DefineSequence: option \"%s\" not recognized",
804 805 806 807 808
				 defel->defname);
	}

	if (increment_by == (DefElem *) NULL)		/* INCREMENT BY */
		new->increment_by = 1;
809
	else if ((new->increment_by = defGetInt64(increment_by)) == 0)
810
		elog(ERROR, "DefineSequence: can't INCREMENT by 0");
811 812

	if (max_value == (DefElem *) NULL)	/* MAXVALUE */
813
	{
814 815 816
		if (new->increment_by > 0)
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
		else
817
			new->max_value = -1;	/* descending seq */
818
	}
819
	else
820
		new->max_value = defGetInt64(max_value);
821

822
	if (min_value == (DefElem *) NULL)	/* MINVALUE */
823
	{
824 825 826 827
		if (new->increment_by > 0)
			new->min_value = 1; /* ascending seq */
		else
			new->min_value = SEQ_MINVALUE;		/* descending seq */
828
	}
829
	else
830
		new->min_value = defGetInt64(min_value);
831 832

	if (new->min_value >= new->max_value)
833
	{
B
Bruce Momjian 已提交
834 835 836
		char		bufm[100],
					bufx[100];

837 838 839 840 841
		snprintf(bufm, 100, INT64_FORMAT, new->min_value);
		snprintf(bufx, 100, INT64_FORMAT, new->max_value);
		elog(ERROR, "DefineSequence: MINVALUE (%s) must be less than MAXVALUE (%s)",
			 bufm, bufx);
	}
842 843

	if (last_value == (DefElem *) NULL) /* START WITH */
844
	{
845 846 847 848
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
849
	}
850
	else
851
		new->last_value = defGetInt64(last_value);
852 853

	if (new->last_value < new->min_value)
854
	{
B
Bruce Momjian 已提交
855 856 857
		char		bufs[100],
					bufm[100];

858 859 860 861 862
		snprintf(bufs, 100, INT64_FORMAT, new->last_value);
		snprintf(bufm, 100, INT64_FORMAT, new->min_value);
		elog(ERROR, "DefineSequence: START value (%s) can't be less than MINVALUE (%s)",
			 bufs, bufm);
	}
863
	if (new->last_value > new->max_value)
864
	{
B
Bruce Momjian 已提交
865 866 867
		char		bufs[100],
					bufm[100];

868 869 870 871 872
		snprintf(bufs, 100, INT64_FORMAT, new->last_value);
		snprintf(bufm, 100, INT64_FORMAT, new->max_value);
		elog(ERROR, "DefineSequence: START value (%s) can't be greater than MAXVALUE (%s)",
			 bufs, bufm);
	}
873 874 875

	if (cache_value == (DefElem *) NULL)		/* CACHE */
		new->cache_value = 1;
876
	else if ((new->cache_value = defGetInt64(cache_value)) <= 0)
877
	{
B
Bruce Momjian 已提交
878 879
		char		buf[100];

880 881 882 883
		snprintf(buf, 100, INT64_FORMAT, new->cache_value);
		elog(ERROR, "DefineSequence: CACHE (%s) can't be <= 0",
			 buf);
	}
884 885 886

}

V
Vadim B. Mikheev 已提交
887

B
Bruce Momjian 已提交
888 889
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
890
{
B
Bruce Momjian 已提交
891 892 893 894 895 896 897
	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);
898
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
899

900
	if (info != XLOG_SEQ_LOG)
901
		elog(PANIC, "seq_redo: unknown op code %u", info);
V
Vadim B. Mikheev 已提交
902 903 904 905 906

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

907
	buffer = XLogReadBuffer(true, reln, 0);
V
Vadim B. Mikheev 已提交
908
	if (!BufferIsValid(buffer))
909
		elog(PANIC, "seq_redo: can't read block of %u/%u",
B
Bruce Momjian 已提交
910
			 xlrec->node.tblNode, xlrec->node.relNode);
V
Vadim B. Mikheev 已提交
911 912 913

	page = (Page) BufferGetPage(buffer);

914 915
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
916 917 918
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
919

B
Bruce Momjian 已提交
920
	item = (char *) xlrec + sizeof(xl_seq_rec);
921 922
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
923
	if (PageAddItem(page, (Item) item, itemsz,
924
					FirstOffsetNumber, LP_USED) == InvalidOffsetNumber)
925
		elog(PANIC, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
926 927 928 929 930 931

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

B
Bruce Momjian 已提交
932 933
void
seq_undo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
934 935 936
{
}

B
Bruce Momjian 已提交
937 938
void
seq_desc(char *buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
939
{
B
Bruce Momjian 已提交
940 941
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
942 943 944 945 946 947 948 949 950

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

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