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.73 2002/03/21 23:27:21 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

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

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

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

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

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

476
	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 508 509 510
	/* open and AccessShareLock sequence */
	elm = init_sequence("setval", seqname);

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

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

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

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

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

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

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

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

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

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

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

	pfree(seqname);
565 566
}

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

	do_setval(seqname, next, true);

580
	PG_RETURN_INT64(next);
581 582
}

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

	do_setval(seqname, next, iscalled);

597
	PG_RETURN_INT64(next);
598 599 600 601
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	elm->increment = seq->increment_by;

687
	return seq;
688 689 690
}


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

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

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

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

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

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

753
	return elm;
754 755 756 757
}


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

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


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

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

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

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

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

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

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

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

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

}

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

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

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

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

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

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

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

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

	page = (Page) BufferGetPage(buffer);

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

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

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

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

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

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

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