sequence.c 24.2 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.75 2002/03/29 19:06:07 tgl Exp $
12
 *
13 14
 *-------------------------------------------------------------------------
 */
15
#include "postgres.h"
16

17 18
#include <ctype.h>

19
#include "access/heapam.h"
20
#include "catalog/pg_type.h"
21 22
#include "commands/creatinh.h"
#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
#include "utils/int8.h"
27 28 29 30
#ifdef MULTIBYTE
#include "mb/pg_wchar.h"
#endif

31

32
#define SEQ_MAGIC	  0x1717
33

34 35 36 37 38 39
#ifndef INT64_IS_BUSTED
#ifdef HAVE_LL_CONSTANTS
#define SEQ_MAXVALUE	((int64) 0x7FFFFFFFFFFFFFFFLL)
#else
#define SEQ_MAXVALUE	((int64) 0x7FFFFFFFFFFFFFFF)
#endif
40
#else							/* INT64_IS_BUSTED */
41
#define SEQ_MAXVALUE	((int64) 0x7FFFFFFF)
42
#endif   /* INT64_IS_BUSTED */
43 44

#define SEQ_MINVALUE	(-SEQ_MAXVALUE)
45

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

typedef struct sequence_magic
{
55
	uint32		magic;
56
} sequence_magic;
57

58 59
typedef struct SeqTableData
{
60 61
	char	   *name;
	Oid			relid;
62 63 64 65
	Relation	rel;			/* NULL if rel is not open in cur xact */
	int64		cached;
	int64		last;
	int64		increment;
66
	struct SeqTableData *next;
67
} SeqTableData;
68 69 70 71 72

typedef SeqTableData *SeqTable;

static SeqTable seqtab = NULL;

73
static char *get_seq_name(text *seqin);
74
static SeqTable init_sequence(char *caller, char *name);
75 76
static Form_pg_sequence read_info(char *caller, SeqTable elm, Buffer *buf);
static void init_params(CreateSeqStmt *seq, Form_pg_sequence new);
77 78
static int64 get_param(DefElem *def);
static void do_setval(char *seqname, int64 next, bool iscalled);
79 80

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

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

	/*
105
	 * Create relation (and fill *null & *value)
106 107 108
	 */
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
109
	{
110 111 112
		ColumnDef  *coldef;
		TypeName   *typnam;

113 114
		typnam = makeNode(TypeName);
		typnam->setof = FALSE;
115
		typnam->arrayBounds = NIL;
B
Bruce Momjian 已提交
116
		typnam->typmod = -1;
117 118
		coldef = makeNode(ColumnDef);
		coldef->typename = typnam;
119 120
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
121 122 123 124 125
		coldef->is_not_null = false;
		null[i - 1] = ' ';

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

176 177
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
178
	stmt->constraints = NIL;
179
	stmt->hasoids = false;
180

181
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
182

183
	rel = heap_open(seqoid, AccessExclusiveLock);
184
	tupDesc = RelationGetDescr(rel);
185

186 187
	/* Initialize first page of relation with special magic number */

188 189 190
	buf = ReadBuffer(rel, P_NEW);

	if (!BufferIsValid(buf))
191
		elog(ERROR, "DefineSequence: ReadBuffer failed");
192

193 194
	Assert(BufferGetBlockNumber(buf) == 0);

195 196 197 198 199 200
	page = (PageHeader) BufferGetPage(buf);

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

201 202 203
	/* hack: ensure heap_insert will insert on the just-created page */
	rel->rd_targblock = 0;

204
	/* Now form & insert sequence tuple */
205 206 207
	tuple = heap_formtuple(tupDesc, value, null);
	heap_insert(rel, tuple);

208 209
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

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

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

249
	{
250 251 252 253
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];
		Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
254 255

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

278
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);
279 280
	WriteBuffer(buf);
	heap_close(rel, NoLock);
281 282 283
}


284 285
Datum
nextval(PG_FUNCTION_ARGS)
286
{
287 288
	text	   *seqin = PG_GETARG_TEXT_P(0);
	char	   *seqname = get_seq_name(seqin);
289 290
	SeqTable	elm;
	Buffer		buf;
291
	Page		page;
292
	Form_pg_sequence seq;
293
	int64		incby,
294 295
				maxv,
				minv,
V
Vadim B. Mikheev 已提交
296 297 298 299
				cache,
				log,
				fetch,
				last;
300
	int64		result,
301 302
				next,
				rescnt = 0;
V
Vadim B. Mikheev 已提交
303
	bool		logit = false;
304

V
Vadim B. Mikheev 已提交
305
	/* open and AccessShareLock sequence */
306
	elm = init_sequence("nextval", seqname);
307

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

312 313 314 315 316
	pfree(seqname);

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
		elm->last += elm->increment;
317
		PG_RETURN_INT64(elm->last);
318
	}
319

B
Bruce Momjian 已提交
320 321
	seq = read_info("nextval", elm, &buf);		/* lock page' buffer and
												 * read tuple */
322
	page = BufferGetPage(buf);
323

V
Vadim B. Mikheev 已提交
324
	last = next = result = seq->last_value;
325 326 327
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
328 329
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
330

331
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
332
	{
333
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
334 335 336
		fetch--;
		log--;
	}
337

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

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

415 416 417
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

418 419
	/* save info in local cache */
	elm->last = result;			/* last returned number */
V
Vadim B. Mikheev 已提交
420 421
	elm->cached = last;			/* last fetched number */

422
	START_CRIT_SECTION();
V
Vadim B. Mikheev 已提交
423 424 425 426
	if (logit)
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
427
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
428 429

		xlrec.node = elm->rel->rd_node;
430
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
431
		rdata[0].data = (char *) &xlrec;
432 433 434 435
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

		seq->last_value = next;
436
		seq->is_called = true;
437 438
		seq->log_cnt = 0;
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
439 440 441
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
442 443
		rdata[1].next = NULL;

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

446 447
		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
448
	}
449

450
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
451
	seq->last_value = last;		/* last fetched number */
452
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
453
	seq->log_cnt = log;			/* how much is logged */
454
	END_CRIT_SECTION();
455

V
Vadim B. Mikheev 已提交
456 457
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

458
	if (WriteBuffer(buf) == STATUS_ERROR)
459
		elog(ERROR, "%s.nextval: WriteBuffer failed", elm->name);
460

461
	PG_RETURN_INT64(result);
462 463
}

464 465
Datum
currval(PG_FUNCTION_ARGS)
466
{
467 468
	text	   *seqin = PG_GETARG_TEXT_P(0);
	char	   *seqname = get_seq_name(seqin);
469
	SeqTable	elm;
470
	int64		result;
471

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

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

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

	result = elm->last;

485
	pfree(seqname);
486

487
	PG_RETURN_INT64(result);
488 489
}

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

510 511 512 513
	/* open and AccessShareLock sequence */
	elm = init_sequence("setval", seqname);

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

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

520
	if ((next < seq->min_value) || (next > seq->max_value))
521
		elog(ERROR, "%s.setval: value " INT64_FORMAT " is out of bounds (" INT64_FORMAT "," INT64_FORMAT ")",
522
			 seqname, next, seq->min_value, seq->max_value);
M
 
Marc G. Fournier 已提交
523 524 525

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

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

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

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

B
Bruce Momjian 已提交
551
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);
552 553 554

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

V
Vadim B. Mikheev 已提交
562 563
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

564
	if (WriteBuffer(buf) == STATUS_ERROR)
565 566 567
		elog(ERROR, "%s.setval: WriteBuffer failed", seqname);

	pfree(seqname);
568 569
}

570 571 572 573
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
574 575 576 577
Datum
setval(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
578
	int64		next = PG_GETARG_INT64(1);
579 580 581 582
	char	   *seqname = get_seq_name(seqin);

	do_setval(seqname, next, true);

583
	PG_RETURN_INT64(next);
584 585
}

586 587 588 589
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
590 591 592 593
Datum
setval_and_iscalled(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
594
	int64		next = PG_GETARG_INT64(1);
595 596 597 598 599
	bool		iscalled = PG_GETARG_BOOL(2);
	char	   *seqname = get_seq_name(seqin);

	do_setval(seqname, next, iscalled);

600
	PG_RETURN_INT64(next);
601 602 603 604
}

/*
 * Given a 'text' parameter to a sequence function, extract the actual
605 606
 * sequence name.  We downcase the name if it's not double-quoted,
 * and truncate it if it's too long.
607 608 609 610 611 612
 *
 * This is a kluge, really --- should be able to write nextval(seqrel).
 */
static char *
get_seq_name(text *seqin)
{
613
	char	   *rawname = DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
614
												PointerGetDatum(seqin)));
615 616
	int			rawlen = strlen(rawname);
	char	   *seqname;
M
 
Marc G. Fournier 已提交
617

618 619 620 621 622 623 624 625 626 627 628
	if (rawlen >= 2 &&
		rawname[0] == '\"' && rawname[rawlen - 1] == '\"')
	{
		/* strip off quotes, keep case */
		rawname[rawlen - 1] = '\0';
		seqname = pstrdup(rawname + 1);
		pfree(rawname);
	}
	else
	{
		seqname = rawname;
B
Bruce Momjian 已提交
629

630 631 632 633 634 635
		/*
		 * It's important that this match the identifier downcasing code
		 * used by backend/parser/scan.l.
		 */
		for (; *rawname; rawname++)
		{
636 637
			if (isupper((unsigned char) *rawname))
				*rawname = tolower((unsigned char) *rawname);
638 639
		}
	}
640 641 642 643 644

	/* Truncate name if it's overlength; again, should match scan.l */
	if (strlen(seqname) >= NAMEDATALEN)
	{
#ifdef MULTIBYTE
645
		int			len;
646

647
		len = pg_mbcliplen(seqname, rawlen, NAMEDATALEN - 1);
648 649
		seqname[len] = '\0';
#else
650
		seqname[NAMEDATALEN - 1] = '\0';
651 652 653
#endif
	}

654
	return seqname;
M
 
Marc G. Fournier 已提交
655 656
}

657
static Form_pg_sequence
B
Bruce Momjian 已提交
658
read_info(char *caller, SeqTable elm, Buffer *buf)
659
{
B
Bruce Momjian 已提交
660 661 662
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
663
	sequence_magic *sm;
B
Bruce Momjian 已提交
664
	Form_pg_sequence seq;
665

666
	if (elm->rel->rd_nblocks > 1)
667
		elog(ERROR, "%s.%s: invalid number of blocks in sequence",
668 669 670 671
			 elm->name, caller);

	*buf = ReadBuffer(elm->rel, 0);
	if (!BufferIsValid(*buf))
672
		elog(ERROR, "%s.%s: ReadBuffer failed", elm->name, caller);
673

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

676 677 678 679
	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
680
		elog(ERROR, "%s.%s: bad magic (%08X)", elm->name, caller, sm->magic);
681 682 683

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

686
	seq = (Form_pg_sequence) GETSTRUCT(&tuple);
687 688 689

	elm->increment = seq->increment_by;

690
	return seq;
691 692 693
}


694
static SeqTable
695
init_sequence(char *caller, char *name)
696
{
697
	SeqTable	elm,
698 699
				prev = (SeqTable) NULL;
	Relation	seqrel;
700

701 702
	/* Look to see if we already have a seqtable entry for name */
	for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next)
703 704 705
	{
		if (strcmp(elm->name, name) == 0)
			break;
706
		prev = elm;
707 708
	}

709 710 711
	/* 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;
712

713 714 715
	/* Else open and check it */
	seqrel = heap_openr(name, AccessShareLock);
	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
716
		elog(ERROR, "%s.%s: %s is not a sequence", name, caller, name);
717

718 719
	if (elm != (SeqTable) NULL)
	{
720 721
		/*
		 * We are using a seqtable entry left over from a previous xact;
722 723 724 725
		 * must check for relid change.
		 */
		elm->rel = seqrel;
		if (RelationGetRelid(seqrel) != elm->relid)
726
		{
B
Bruce Momjian 已提交
727
			elog(WARNING, "%s.%s: sequence was re-created",
728
				 name, caller);
729
			elm->relid = RelationGetRelid(seqrel);
730 731 732 733 734
			elm->cached = elm->last = elm->increment = 0;
		}
	}
	else
	{
735 736
		/*
		 * Time to make a new seqtable entry.  These entries live as long
737 738 739
		 * as the backend does, so we use plain malloc for them.
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
740 741 742 743 744
		if (elm == NULL)
			elog(ERROR, "Memory exhausted in init_sequence");
		elm->name = strdup(name);
		if (elm->name == NULL)
			elog(ERROR, "Memory exhausted in init_sequence");
745 746 747 748 749
		elm->rel = seqrel;
		elm->relid = RelationGetRelid(seqrel);
		elm->cached = elm->last = elm->increment = 0;
		elm->next = (SeqTable) NULL;

750 751 752
		if (seqtab == (SeqTable) NULL)
			seqtab = elm;
		else
753
			prev->next = elm;
754 755
	}

756
	return elm;
757 758 759 760
}


/*
B
Bruce Momjian 已提交
761
 * CloseSequences
762
 *				is called by xact mgr at commit/abort.
763 764
 */
void
765
CloseSequences(void)
766
{
767 768
	SeqTable	elm;
	Relation	rel;
769

770
	for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next)
771
	{
772
		rel = elm->rel;
773
		if (rel != (Relation) NULL)		/* opened in current xact */
774 775
		{
			elm->rel = (Relation) NULL;
776
			heap_close(rel, AccessShareLock);
777 778
		}
	}
779 780 781
}


782
static void
783
init_params(CreateSeqStmt *seq, Form_pg_sequence new)
784
{
785 786 787 788 789 790
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
	List	   *option;
791

792
	new->is_cycled = false;
793 794
	foreach(option, seq->options)
	{
795
		DefElem    *defel = (DefElem *) lfirst(option);
796

797
		if (strcmp(defel->defname, "increment") == 0)
798
			increment_by = defel;
799
		else if (strcmp(defel->defname, "start") == 0)
800
			last_value = defel;
801
		else if (strcmp(defel->defname, "maxvalue") == 0)
802
			max_value = defel;
803
		else if (strcmp(defel->defname, "minvalue") == 0)
804
			min_value = defel;
805
		else if (strcmp(defel->defname, "cache") == 0)
806
			cache_value = defel;
807
		else if (strcmp(defel->defname, "cycle") == 0)
808 809
		{
			if (defel->arg != (Node *) NULL)
810
				elog(ERROR, "DefineSequence: CYCLE ??");
811
			new->is_cycled = true;
812 813
		}
		else
814
			elog(ERROR, "DefineSequence: option \"%s\" not recognized",
815 816 817 818 819 820
				 defel->defname);
	}

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

	if (max_value == (DefElem *) NULL)	/* MAXVALUE */
824
	{
825 826 827
		if (new->increment_by > 0)
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
		else
828
			new->max_value = -1;	/* descending seq */
829
	}
830
	else
831
		new->max_value = get_param(max_value);
832

833
	if (min_value == (DefElem *) NULL)	/* MINVALUE */
834
	{
835 836 837 838
		if (new->increment_by > 0)
			new->min_value = 1; /* ascending seq */
		else
			new->min_value = SEQ_MINVALUE;		/* descending seq */
839
	}
840
	else
841 842 843
		new->min_value = get_param(min_value);

	if (new->min_value >= new->max_value)
844
		elog(ERROR, "DefineSequence: MINVALUE (" INT64_FORMAT ") can't be >= MAXVALUE (" INT64_FORMAT ")",
845 846 847
			 new->min_value, new->max_value);

	if (last_value == (DefElem *) NULL) /* START WITH */
848
	{
849 850 851 852
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
853
	}
854
	else
855 856 857
		new->last_value = get_param(last_value);

	if (new->last_value < new->min_value)
858
		elog(ERROR, "DefineSequence: START value (" INT64_FORMAT ") can't be < MINVALUE (" INT64_FORMAT ")",
859 860
			 new->last_value, new->min_value);
	if (new->last_value > new->max_value)
861
		elog(ERROR, "DefineSequence: START value (" INT64_FORMAT ") can't be > MAXVALUE (" INT64_FORMAT ")",
862 863 864 865 866
			 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)
867
		elog(ERROR, "DefineSequence: CACHE (" INT64_FORMAT ") can't be <= 0",
868
			 new->cache_value);
869 870 871

}

872
static int64
873
get_param(DefElem *def)
874
{
875
	if (def->arg == (Node *) NULL)
876
		elog(ERROR, "DefineSequence: \"%s\" value unspecified", def->defname);
877

878 879
	if (IsA(def->arg, Integer))
		return (int64) intVal(def->arg);
880

881
	/*
882 883
	 * Values too large for int4 will be represented as Float constants by
	 * the lexer.  Accept these if they are valid int8 strings.
884 885 886
	 */
	if (IsA(def->arg, Float))
		return DatumGetInt64(DirectFunctionCall1(int8in,
887
									 CStringGetDatum(strVal(def->arg))));
888 889

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

B
Bruce Momjian 已提交
894 895
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
896
{
B
Bruce Momjian 已提交
897 898 899 900 901 902 903
	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);
904
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
905

906
	if (info != XLOG_SEQ_LOG)
907
		elog(PANIC, "seq_redo: unknown op code %u", info);
V
Vadim B. Mikheev 已提交
908 909 910 911 912

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

913
	buffer = XLogReadBuffer(true, reln, 0);
V
Vadim B. Mikheev 已提交
914
	if (!BufferIsValid(buffer))
915
		elog(PANIC, "seq_redo: can't read block of %u/%u",
B
Bruce Momjian 已提交
916
			 xlrec->node.tblNode, xlrec->node.relNode);
V
Vadim B. Mikheev 已提交
917 918 919

	page = (Page) BufferGetPage(buffer);

920 921
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
922 923 924
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
925

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

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

B
Bruce Momjian 已提交
938 939
void
seq_undo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
940 941 942
{
}

B
Bruce Momjian 已提交
943 944
void
seq_desc(char *buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
945
{
B
Bruce Momjian 已提交
946 947
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
948 949 950 951 952 953 954 955 956

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

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