sequence.c 24.1 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.72 2002/03/21 16:00:33 tgl Exp $
12
 *
13 14
 *-------------------------------------------------------------------------
 */
15
#include "postgres.h"
16

17 18
#include <ctype.h>

19 20 21
#include "access/heapam.h"
#include "commands/creatinh.h"
#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 29
#ifdef MULTIBYTE
#include "mb/pg_wchar.h"
#endif

30

31
#define SEQ_MAGIC	  0x1717
32

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

#define SEQ_MINVALUE	(-SEQ_MAXVALUE)
44

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

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

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

typedef SeqTableData *SeqTable;

static SeqTable seqtab = NULL;

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

/*
B
Bruce Momjian 已提交
80
 * DefineSequence
81
 *				Creates a new sequence relation
82 83
 */
void
84
DefineSequence(CreateSeqStmt *seq)
85
{
86
	FormData_pg_sequence new;
87 88 89 90 91 92
	CreateStmt *stmt = makeNode(CreateStmt);
	ColumnDef  *coldef;
	TypeName   *typnam;
	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
		typnam = makeNode(TypeName);
		typnam->setof = FALSE;
		typnam->arrayBounds = NULL;
B
Bruce Momjian 已提交
113
		typnam->typmod = -1;
114 115
		coldef = makeNode(ColumnDef);
		coldef->typename = typnam;
116 117
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
118 119 120 121 122
		coldef->is_not_null = false;
		null[i - 1] = ' ';

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

173 174
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
175
	stmt->constraints = NIL;
176
	stmt->hasoids = false;
177

178
	DefineRelation(stmt, RELKIND_SEQUENCE);
179

180
	rel = heap_openr(seq->sequence->relname, AccessExclusiveLock);
181
	tupDesc = RelationGetDescr(rel);
182

183 184
	/* Initialize first page of relation with special magic number */

185 186 187
	buf = ReadBuffer(rel, P_NEW);

	if (!BufferIsValid(buf))
188
		elog(ERROR, "DefineSequence: ReadBuffer failed");
189

190 191
	Assert(BufferGetBlockNumber(buf) == 0);

192 193 194 195 196 197
	page = (PageHeader) BufferGetPage(buf);

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

198 199 200
	/* hack: ensure heap_insert will insert on the just-created page */
	rel->rd_targblock = 0;

201
	/* Now form & insert sequence tuple */
202 203 204
	tuple = heap_formtuple(tupDesc, value, null);
	heap_insert(rel, tuple);

205 206
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

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

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

246
	{
247 248 249 250
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];
		Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
251 252

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

275
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);
276 277
	WriteBuffer(buf);
	heap_close(rel, NoLock);
278 279 280
}


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

302
	if (pg_aclcheck(seqname, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
303 304 305
		elog(ERROR, "%s.nextval: you don't have permissions to set sequence %s",
			 seqname, seqname);

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

309 310 311 312 313
	pfree(seqname);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

V
Vadim B. Mikheev 已提交
453 454
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

455
	if (WriteBuffer(buf) == STATUS_ERROR)
456
		elog(ERROR, "%s.nextval: WriteBuffer failed", elm->name);
457

458
	PG_RETURN_INT64(result);
459 460
}

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

469
	if (pg_aclcheck(seqname, GetUserId(), ACL_SELECT) != ACLCHECK_OK)
470 471
		elog(ERROR, "%s.currval: you don't have permissions to read sequence %s",
			 seqname, seqname);
472

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

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

	result = elm->last;

482
	pfree(seqname);
483

484
	PG_RETURN_INT64(result);
485 486
}

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

507
	if (pg_aclcheck(seqname, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
M
 
Marc G. Fournier 已提交
508 509 510
		elog(ERROR, "%s.setval: you don't have permissions to set sequence %s",
			 seqname, seqname);

V
Vadim B. Mikheev 已提交
511
	/* open and AccessShareLock sequence */
512
	elm = init_sequence("setval", seqname);
B
Bruce Momjian 已提交
513 514
	seq = read_info("setval", elm, &buf);		/* lock page' buffer and
												 * read tuple */
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
			 seqname, 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 562 563
		elog(ERROR, "%s.setval: WriteBuffer failed", seqname);

	pfree(seqname);
564 565
}

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

	do_setval(seqname, next, true);

579
	PG_RETURN_INT64(next);
580 581
}

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

	do_setval(seqname, next, iscalled);

596
	PG_RETURN_INT64(next);
597 598 599 600
}

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

614 615 616 617 618 619 620 621 622 623 624
	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 已提交
625

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

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

643
		len = pg_mbcliplen(seqname, rawlen, NAMEDATALEN - 1);
644 645
		seqname[len] = '\0';
#else
646
		seqname[NAMEDATALEN - 1] = '\0';
647 648 649
#endif
	}

650
	return seqname;
M
 
Marc G. Fournier 已提交
651 652
}

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

662
	if (elm->rel->rd_nblocks > 1)
663
		elog(ERROR, "%s.%s: invalid number of blocks in sequence",
664 665 666 667
			 elm->name, caller);

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

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

672 673 674 675
	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
676
		elog(ERROR, "%s.%s: bad magic (%08X)", elm->name, caller, sm->magic);
677 678 679

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

682
	seq = (Form_pg_sequence) GETSTRUCT(&tuple);
683 684 685

	elm->increment = seq->increment_by;

686
	return seq;
687 688 689
}


690
static SeqTable
691
init_sequence(char *caller, char *name)
692
{
693
	SeqTable	elm,
694 695
				prev = (SeqTable) NULL;
	Relation	seqrel;
696

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

705 706 707
	/* 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;
708

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

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

746 747 748
		if (seqtab == (SeqTable) NULL)
			seqtab = elm;
		else
749
			prev->next = elm;
750 751
	}

752
	return elm;
753 754 755 756
}


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

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


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

788
	new->is_cycled = false;
789 790
	foreach(option, seq->options)
	{
791
		DefElem    *defel = (DefElem *) lfirst(option);
792

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

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

	if (max_value == (DefElem *) NULL)	/* MAXVALUE */
820
	{
821 822 823
		if (new->increment_by > 0)
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
		else
824
			new->max_value = -1;	/* descending seq */
825
	}
826
	else
827
		new->max_value = get_param(max_value);
828

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

	if (new->min_value >= new->max_value)
840
		elog(ERROR, "DefineSequence: MINVALUE (" INT64_FORMAT ") can't be >= MAXVALUE (" INT64_FORMAT ")",
841 842 843
			 new->min_value, new->max_value);

	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 852 853
		new->last_value = get_param(last_value);

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

}

868
static int64
869
get_param(DefElem *def)
870
{
871
	if (def->arg == (Node *) NULL)
872
		elog(ERROR, "DefineSequence: \"%s\" value unspecified", def->defname);
873

874 875
	if (IsA(def->arg, Integer))
		return (int64) intVal(def->arg);
876

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

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

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

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

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

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

	page = (Page) BufferGetPage(buffer);

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

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

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

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

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

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

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