sequence.c 23.4 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.68 2002/01/11 18:16:04 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 127
				namestrcpy(&name, seq->seqname);
				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 173 174 175
		}
		stmt->tableElts = lappend(stmt->tableElts, coldef);
	}

	stmt->relname = seq->seqname;
	stmt->inhRelnames = NIL;
	stmt->constraints = NIL;
176 177
	stmt->istemp = seq->istemp;
	stmt->hasoids = false;
178

179
	DefineRelation(stmt, RELKIND_SEQUENCE);
180

181
	rel = heap_openr(seq->seqname, 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
	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

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

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

V
Vadim B. Mikheev 已提交
334 335 336 337 338 339
	if (log < fetch)
	{
		fetch = log = fetch - log + SEQ_LOG_VALS;
		logit = true;
	}

B
Bruce Momjian 已提交
340
	while (fetch)				/* try to fetch cache [+ log ] numbers */
341
	{
342 343 344 345
		/*
		 * Check MAXVALUE for ascending sequences and MINVALUE for
		 * descending sequences
		 */
346
		if (incby > 0)
347
		{
348
			/* ascending sequence */
349 350 351 352
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
353
					break;		/* stop fetching */
354 355
				if (!seq->is_cycled)
					elog(ERROR, "%s.nextval: reached MAXVALUE (" INT64_FORMAT ")",
356 357 358 359 360 361 362 363
						 elm->name, maxv);
				next = minv;
			}
			else
				next += incby;
		}
		else
		{
364
			/* descending sequence */
365 366 367 368
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
369
					break;		/* stop fetching */
370 371
				if (!seq->is_cycled)
					elog(ERROR, "%s.nextval: reached MINVALUE (" INT64_FORMAT ")",
372 373 374 375 376 377
						 elm->name, minv);
				next = maxv;
			}
			else
				next += incby;
		}
V
Vadim B. Mikheev 已提交
378 379 380 381 382 383
		fetch--;
		if (rescnt < cache)
		{
			log--;
			rescnt++;
			last = next;
B
Bruce Momjian 已提交
384 385
			if (rescnt == 1)	/* if it's first result - */
				result = next;	/* it's what to return */
V
Vadim B. Mikheev 已提交
386
		}
387 388 389 390
	}

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

393
	START_CRIT_SECTION();
V
Vadim B. Mikheev 已提交
394 395 396 397
	if (logit)
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
398
		XLogRecData rdata[2];
399
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
400 401

		xlrec.node = elm->rel->rd_node;
402
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
403
		rdata[0].data = (char *) &xlrec;
404 405 406 407
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

		seq->last_value = next;
408
		seq->is_called = true;
409 410
		seq->log_cnt = 0;
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
411 412 413
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
414 415
		rdata[1].next = NULL;

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

418 419
		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
420

B
Bruce Momjian 已提交
421
		if (fetch)				/* not all numbers were fetched */
422
			log -= fetch;
V
Vadim B. Mikheev 已提交
423
	}
424

425
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
426
	seq->last_value = last;		/* last fetched number */
427
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
428 429
	Assert(log >= 0);
	seq->log_cnt = log;			/* how much is logged */
430
	END_CRIT_SECTION();
431

V
Vadim B. Mikheev 已提交
432 433
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

434
	if (WriteBuffer(buf) == STATUS_ERROR)
435
		elog(ERROR, "%s.nextval: WriteBuffer failed", elm->name);
436

437
	PG_RETURN_INT64(result);
438 439
}

440 441
Datum
currval(PG_FUNCTION_ARGS)
442
{
443 444
	text	   *seqin = PG_GETARG_TEXT_P(0);
	char	   *seqname = get_seq_name(seqin);
445
	SeqTable	elm;
446
	int64		result;
447

448
	if (pg_aclcheck(seqname, GetUserId(), ACL_SELECT) != ACLCHECK_OK)
449 450
		elog(ERROR, "%s.currval: you don't have permissions to read sequence %s",
			 seqname, seqname);
451

V
Vadim B. Mikheev 已提交
452
	/* open and AccessShareLock sequence */
453 454 455
	elm = init_sequence("currval", seqname);

	if (elm->increment == 0)	/* nextval/read_info were not called */
456 457
		elog(ERROR, "%s.currval is not yet defined in this session",
			 seqname);
458 459 460

	result = elm->last;

461
	pfree(seqname);
462

463
	PG_RETURN_INT64(result);
464 465
}

B
Bruce Momjian 已提交
466
/*
467 468 469 470
 * 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 已提交
471
 * work if multiple users are attached to the database and referencing
472 473
 * the sequence (unlikely if pg_dump is restoring it).
 *
B
Bruce Momjian 已提交
474
 * It is necessary to have the 3 arg version so that pg_dump can
475 476 477 478
 * 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 已提交
479
static void
480
do_setval(char *seqname, int64 next, bool iscalled)
M
 
Marc G. Fournier 已提交
481 482
{
	SeqTable	elm;
483
	Buffer		buf;
484
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
485

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

V
Vadim B. Mikheev 已提交
490
	/* open and AccessShareLock sequence */
491
	elm = init_sequence("setval", seqname);
B
Bruce Momjian 已提交
492 493
	seq = read_info("setval", elm, &buf);		/* lock page' buffer and
												 * read tuple */
M
 
Marc G. Fournier 已提交
494

495
	if ((next < seq->min_value) || (next > seq->max_value))
496
		elog(ERROR, "%s.setval: value " INT64_FORMAT " is out of bounds (" INT64_FORMAT "," INT64_FORMAT ")",
497
			 seqname, next, seq->min_value, seq->max_value);
M
 
Marc G. Fournier 已提交
498 499 500

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

504
	START_CRIT_SECTION();
V
Vadim B. Mikheev 已提交
505 506 507
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
508
		XLogRecData rdata[2];
509
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
510 511

		xlrec.node = elm->rel->rd_node;
512
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
513
		rdata[0].data = (char *) &xlrec;
514 515 516 517
		rdata[0].len = sizeof(xl_seq_rec);
		rdata[0].next = &(rdata[1]);

		seq->last_value = next;
518
		seq->is_called = true;
519 520
		seq->log_cnt = 0;
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
521 522 523
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
524 525
		rdata[1].next = NULL;

B
Bruce Momjian 已提交
526
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);
527 528 529

		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
V
Vadim B. Mikheev 已提交
530
	}
531 532
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
533
	seq->is_called = iscalled;
534
	seq->log_cnt = (iscalled) ? 0 : 1;
535
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
536

V
Vadim B. Mikheev 已提交
537 538
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

539
	if (WriteBuffer(buf) == STATUS_ERROR)
540 541 542
		elog(ERROR, "%s.setval: WriteBuffer failed", seqname);

	pfree(seqname);
543 544
}

545 546 547 548
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
549 550 551 552
Datum
setval(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
553
	int64		next = PG_GETARG_INT64(1);
554 555 556 557
	char	   *seqname = get_seq_name(seqin);

	do_setval(seqname, next, true);

558
	PG_RETURN_INT64(next);
559 560
}

561 562 563 564
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
565 566 567 568
Datum
setval_and_iscalled(PG_FUNCTION_ARGS)
{
	text	   *seqin = PG_GETARG_TEXT_P(0);
569
	int64		next = PG_GETARG_INT64(1);
570 571 572 573 574
	bool		iscalled = PG_GETARG_BOOL(2);
	char	   *seqname = get_seq_name(seqin);

	do_setval(seqname, next, iscalled);

575
	PG_RETURN_INT64(next);
576 577 578 579
}

/*
 * Given a 'text' parameter to a sequence function, extract the actual
580 581
 * sequence name.  We downcase the name if it's not double-quoted,
 * and truncate it if it's too long.
582 583 584 585 586 587
 *
 * This is a kluge, really --- should be able to write nextval(seqrel).
 */
static char *
get_seq_name(text *seqin)
{
588
	char	   *rawname = DatumGetCString(DirectFunctionCall1(textout,
B
Bruce Momjian 已提交
589
												PointerGetDatum(seqin)));
590 591
	int			rawlen = strlen(rawname);
	char	   *seqname;
M
 
Marc G. Fournier 已提交
592

593 594 595 596 597 598 599 600 601 602 603
	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 已提交
604

605 606 607 608 609 610
		/*
		 * It's important that this match the identifier downcasing code
		 * used by backend/parser/scan.l.
		 */
		for (; *rawname; rawname++)
		{
611 612
			if (isupper((unsigned char) *rawname))
				*rawname = tolower((unsigned char) *rawname);
613 614
		}
	}
615 616 617 618 619

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

622
		len = pg_mbcliplen(seqname, rawlen, NAMEDATALEN - 1);
623 624
		seqname[len] = '\0';
#else
625
		seqname[NAMEDATALEN - 1] = '\0';
626 627 628
#endif
	}

629
	return seqname;
M
 
Marc G. Fournier 已提交
630 631
}

632
static Form_pg_sequence
B
Bruce Momjian 已提交
633
read_info(char *caller, SeqTable elm, Buffer *buf)
634
{
B
Bruce Momjian 已提交
635 636 637
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
638
	sequence_magic *sm;
B
Bruce Momjian 已提交
639
	Form_pg_sequence seq;
640

641
	if (elm->rel->rd_nblocks > 1)
642
		elog(ERROR, "%s.%s: invalid number of blocks in sequence",
643 644 645 646
			 elm->name, caller);

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

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

651 652 653 654
	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
655
		elog(ERROR, "%s.%s: bad magic (%08X)", elm->name, caller, sm->magic);
656 657 658

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

661
	seq = (Form_pg_sequence) GETSTRUCT(&tuple);
662 663 664

	elm->increment = seq->increment_by;

665
	return seq;
666 667 668
}


669
static SeqTable
670
init_sequence(char *caller, char *name)
671
{
672
	SeqTable	elm,
673 674
				prev = (SeqTable) NULL;
	Relation	seqrel;
675

676 677
	/* Look to see if we already have a seqtable entry for name */
	for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next)
678 679 680
	{
		if (strcmp(elm->name, name) == 0)
			break;
681
		prev = elm;
682 683
	}

684 685 686
	/* 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;
687

688 689 690
	/* Else open and check it */
	seqrel = heap_openr(name, AccessShareLock);
	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
691
		elog(ERROR, "%s.%s: %s is not a sequence", name, caller, name);
692

693 694
	if (elm != (SeqTable) NULL)
	{
695 696
		/*
		 * We are using a seqtable entry left over from a previous xact;
697 698 699 700
		 * must check for relid change.
		 */
		elm->rel = seqrel;
		if (RelationGetRelid(seqrel) != elm->relid)
701 702
		{
			elog(NOTICE, "%s.%s: sequence was re-created",
703
				 name, caller);
704
			elm->relid = RelationGetRelid(seqrel);
705 706 707 708 709
			elm->cached = elm->last = elm->increment = 0;
		}
	}
	else
	{
710 711
		/*
		 * Time to make a new seqtable entry.  These entries live as long
712 713 714
		 * as the backend does, so we use plain malloc for them.
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
715 716 717 718 719
		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");
720 721 722 723 724
		elm->rel = seqrel;
		elm->relid = RelationGetRelid(seqrel);
		elm->cached = elm->last = elm->increment = 0;
		elm->next = (SeqTable) NULL;

725 726 727
		if (seqtab == (SeqTable) NULL)
			seqtab = elm;
		else
728
			prev->next = elm;
729 730
	}

731
	return elm;
732 733 734 735
}


/*
B
Bruce Momjian 已提交
736
 * CloseSequences
737
 *				is called by xact mgr at commit/abort.
738 739
 */
void
740
CloseSequences(void)
741
{
742 743
	SeqTable	elm;
	Relation	rel;
744

745
	for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next)
746
	{
747
		rel = elm->rel;
748
		if (rel != (Relation) NULL)		/* opened in current xact */
749 750
		{
			elm->rel = (Relation) NULL;
751
			heap_close(rel, AccessShareLock);
752 753
		}
	}
754 755 756
}


757
static void
758
init_params(CreateSeqStmt *seq, Form_pg_sequence new)
759
{
760 761 762 763 764 765
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
	List	   *option;
766

767
	new->is_cycled = false;
768 769
	foreach(option, seq->options)
	{
770
		DefElem    *defel = (DefElem *) lfirst(option);
771

772
		if (strcmp(defel->defname, "increment") == 0)
773
			increment_by = defel;
774
		else if (strcmp(defel->defname, "start") == 0)
775
			last_value = defel;
776
		else if (strcmp(defel->defname, "maxvalue") == 0)
777
			max_value = defel;
778
		else if (strcmp(defel->defname, "minvalue") == 0)
779
			min_value = defel;
780
		else if (strcmp(defel->defname, "cache") == 0)
781
			cache_value = defel;
782
		else if (strcmp(defel->defname, "cycle") == 0)
783 784
		{
			if (defel->arg != (Node *) NULL)
785
				elog(ERROR, "DefineSequence: CYCLE ??");
786
			new->is_cycled = true;
787 788
		}
		else
789
			elog(ERROR, "DefineSequence: option \"%s\" not recognized",
790 791 792 793 794 795
				 defel->defname);
	}

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

	if (max_value == (DefElem *) NULL)	/* MAXVALUE */
799
	{
800 801 802
		if (new->increment_by > 0)
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
		else
803
			new->max_value = -1;	/* descending seq */
804
	}
805
	else
806
		new->max_value = get_param(max_value);
807

808
	if (min_value == (DefElem *) NULL)	/* MINVALUE */
809
	{
810 811 812 813
		if (new->increment_by > 0)
			new->min_value = 1; /* ascending seq */
		else
			new->min_value = SEQ_MINVALUE;		/* descending seq */
814
	}
815
	else
816 817 818
		new->min_value = get_param(min_value);

	if (new->min_value >= new->max_value)
819
		elog(ERROR, "DefineSequence: MINVALUE (" INT64_FORMAT ") can't be >= MAXVALUE (" INT64_FORMAT ")",
820 821 822
			 new->min_value, new->max_value);

	if (last_value == (DefElem *) NULL) /* START WITH */
823
	{
824 825 826 827
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
828
	}
829
	else
830 831 832
		new->last_value = get_param(last_value);

	if (new->last_value < new->min_value)
833
		elog(ERROR, "DefineSequence: START value (" INT64_FORMAT ") can't be < MINVALUE (" INT64_FORMAT ")",
834 835
			 new->last_value, new->min_value);
	if (new->last_value > new->max_value)
836
		elog(ERROR, "DefineSequence: START value (" INT64_FORMAT ") can't be > MAXVALUE (" INT64_FORMAT ")",
837 838 839 840 841
			 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)
842
		elog(ERROR, "DefineSequence: CACHE (" INT64_FORMAT ") can't be <= 0",
843
			 new->cache_value);
844 845 846

}

847
static int64
848
get_param(DefElem *def)
849
{
850
	if (def->arg == (Node *) NULL)
851
		elog(ERROR, "DefineSequence: \"%s\" value unspecified", def->defname);
852

853 854
	if (IsA(def->arg, Integer))
		return (int64) intVal(def->arg);
855

856
	/*
857 858
	 * Values too large for int4 will be represented as Float constants by
	 * the lexer.  Accept these if they are valid int8 strings.
859 860 861
	 */
	if (IsA(def->arg, Float))
		return DatumGetInt64(DirectFunctionCall1(int8in,
862
									 CStringGetDatum(strVal(def->arg))));
863 864

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

B
Bruce Momjian 已提交
869 870
void
seq_redo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
871
{
B
Bruce Momjian 已提交
872 873 874 875 876 877 878
	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);
879
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
880

881 882
	if (info != XLOG_SEQ_LOG)
		elog(STOP, "seq_redo: unknown op code %u", info);
V
Vadim B. Mikheev 已提交
883 884 885 886 887

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

888
	buffer = XLogReadBuffer(true, reln, 0);
V
Vadim B. Mikheev 已提交
889
	if (!BufferIsValid(buffer))
B
Bruce Momjian 已提交
890 891
		elog(STOP, "seq_redo: can't read block of %u/%u",
			 xlrec->node.tblNode, xlrec->node.relNode);
V
Vadim B. Mikheev 已提交
892 893 894

	page = (Page) BufferGetPage(buffer);

895 896
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
897 898 899
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
900

B
Bruce Momjian 已提交
901
	item = (char *) xlrec + sizeof(xl_seq_rec);
902 903
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
904
	if (PageAddItem(page, (Item) item, itemsz,
905 906
					FirstOffsetNumber, LP_USED) == InvalidOffsetNumber)
		elog(STOP, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
907 908 909 910 911 912

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

B
Bruce Momjian 已提交
913 914
void
seq_undo(XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
915 916 917
{
}

B
Bruce Momjian 已提交
918 919
void
seq_desc(char *buf, uint8 xl_info, char *rec)
V
Vadim B. Mikheev 已提交
920
{
B
Bruce Momjian 已提交
921 922
	uint8		info = xl_info & ~XLR_INFO_MASK;
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
923 924 925 926 927 928 929 930 931

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

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