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.74 2002/03/22 02:56:31 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
	CreateStmt *stmt = makeNode(CreateStmt);
	ColumnDef  *coldef;
	TypeName   *typnam;
90
	Oid			seqoid;
91 92 93
	Relation	rel;
	Buffer		buf;
	PageHeader	page;
94
	sequence_magic *sm;
95 96 97 98 99
	HeapTuple	tuple;
	TupleDesc	tupDesc;
	Datum		value[SEQ_COL_LASTCOL];
	char		null[SEQ_COL_LASTCOL];
	int			i;
100
	NameData	name;
101 102 103 104 105

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

	/*
106
	 * Create relation (and fill *null & *value)
107 108 109
	 */
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
110
	{
111 112 113
		typnam = makeNode(TypeName);
		typnam->setof = FALSE;
		typnam->arrayBounds = NULL;
B
Bruce Momjian 已提交
114
		typnam->typmod = -1;
115 116
		coldef = makeNode(ColumnDef);
		coldef->typename = typnam;
117 118
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
119 120 121 122 123
		coldef->is_not_null = false;
		null[i - 1] = ' ';

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

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

179
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE);
180

181
	rel = heap_open(seqoid, AccessExclusiveLock);
182
	tupDesc = RelationGetDescr(rel);
183

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

306 307 308 309
	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);

310 311 312 313 314
	pfree(seqname);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

459
	PG_RETURN_INT64(result);
460 461
}

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

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

473 474 475 476
	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);

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

	result = elm->last;

483
	pfree(seqname);
484

485
	PG_RETURN_INT64(result);
486 487
}

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

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

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

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

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

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

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

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

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

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

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

V
Vadim B. Mikheev 已提交
560 561
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

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

	pfree(seqname);
566 567
}

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

	do_setval(seqname, next, true);

581
	PG_RETURN_INT64(next);
582 583
}

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

	do_setval(seqname, next, iscalled);

598
	PG_RETURN_INT64(next);
599 600 601 602
}

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

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

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

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

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

652
	return seqname;
M
 
Marc G. Fournier 已提交
653 654
}

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

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

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

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

674 675 676 677
	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

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

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

684
	seq = (Form_pg_sequence) GETSTRUCT(&tuple);
685 686 687

	elm->increment = seq->increment_by;

688
	return seq;
689 690 691
}


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

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

707 708 709
	/* 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;
710

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

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

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

754
	return elm;
755 756 757 758
}


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

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


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

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

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

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

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

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

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

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

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

}

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

876 877
	if (IsA(def->arg, Integer))
		return (int64) intVal(def->arg);
878

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

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

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

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

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

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

	page = (Page) BufferGetPage(buffer);

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

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

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

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

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

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

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