sequence.c 14.9 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5 6 7 8
 *
 *-------------------------------------------------------------------------
 */

9 10
#include <ctype.h>

11
#include "postgres.h"
12

13 14 15
#include "access/heapam.h"
#include "commands/creatinh.h"
#include "commands/sequence.h"
B
Bruce Momjian 已提交
16
#include "miscadmin.h"
17
#include "utils/acl.h"
B
Bruce Momjian 已提交
18
#include "utils/builtins.h"
19

20
#define SEQ_MAGIC	  0x1717
21 22 23 24

#define SEQ_MAXVALUE	((int4)0x7FFFFFFF)
#define SEQ_MINVALUE	-(SEQ_MAXVALUE)

25 26
typedef struct FormData_pg_sequence
{
27 28 29 30 31 32 33 34
	NameData	sequence_name;
	int4		last_value;
	int4		increment_by;
	int4		max_value;
	int4		min_value;
	int4		cache_value;
	char		is_cycled;
	char		is_called;
35
} FormData_pg_sequence;
36

37
typedef FormData_pg_sequence *Form_pg_sequence;
38 39 40

typedef struct sequence_magic
{
41
	uint32		magic;
42
} sequence_magic;
43

44 45
typedef struct SeqTableData
{
46 47 48 49 50 51
	char	   *name;
	Oid			relid;
	Relation	rel;
	int4		cached;
	int4		last;
	int4		increment;
52
	struct SeqTableData *next;
53
} SeqTableData;
54 55 56 57 58

typedef SeqTableData *SeqTable;

static SeqTable seqtab = NULL;

59
static char *get_seq_name(text *seqin);
60
static SeqTable init_sequence(char *caller, char *name);
61 62
static Form_pg_sequence read_info(char *caller, SeqTable elm, Buffer *buf);
static void init_params(CreateSeqStmt *seq, Form_pg_sequence new);
63
static int	get_param(DefElem *def);
64 65

/*
B
Bruce Momjian 已提交
66
 * DefineSequence
67
 *				Creates a new sequence relation
68 69
 */
void
70
DefineSequence(CreateSeqStmt *seq)
71
{
72
	FormData_pg_sequence new;
73 74 75 76 77 78
	CreateStmt *stmt = makeNode(CreateStmt);
	ColumnDef  *coldef;
	TypeName   *typnam;
	Relation	rel;
	Buffer		buf;
	PageHeader	page;
79
	sequence_magic *sm;
80 81 82 83 84
	HeapTuple	tuple;
	TupleDesc	tupDesc;
	Datum		value[SEQ_COL_LASTCOL];
	char		null[SEQ_COL_LASTCOL];
	int			i;
85
	NameData	name;
86 87 88 89 90

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

	/*
91
	 * Create relation (and fill *null & *value)
92 93 94
	 */
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
95
	{
96 97 98
		typnam = makeNode(TypeName);
		typnam->setof = FALSE;
		typnam->arrayBounds = NULL;
B
Bruce Momjian 已提交
99
		typnam->typmod = -1;
100 101
		coldef = makeNode(ColumnDef);
		coldef->typename = typnam;
102 103
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
104 105 106 107 108
		coldef->is_not_null = false;
		null[i - 1] = ' ';

		switch (i)
		{
109 110 111
			case SEQ_COL_NAME:
				typnam->name = "name";
				coldef->colname = "sequence_name";
112 113
				namestrcpy(&name, seq->seqname);
				value[i - 1] = NameGetDatum(&name);
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
				break;
			case SEQ_COL_LASTVAL:
				typnam->name = "int4";
				coldef->colname = "last_value";
				value[i - 1] = Int32GetDatum(new.last_value);
				break;
			case SEQ_COL_INCBY:
				typnam->name = "int4";
				coldef->colname = "increment_by";
				value[i - 1] = Int32GetDatum(new.increment_by);
				break;
			case SEQ_COL_MAXVALUE:
				typnam->name = "int4";
				coldef->colname = "max_value";
				value[i - 1] = Int32GetDatum(new.max_value);
				break;
			case SEQ_COL_MINVALUE:
				typnam->name = "int4";
				coldef->colname = "min_value";
				value[i - 1] = Int32GetDatum(new.min_value);
				break;
			case SEQ_COL_CACHE:
				typnam->name = "int4";
				coldef->colname = "cache_value";
				value[i - 1] = Int32GetDatum(new.cache_value);
				break;
			case SEQ_COL_CYCLE:
				typnam->name = "char";
				coldef->colname = "is_cycled";
				value[i - 1] = CharGetDatum(new.is_cycled);
				break;
			case SEQ_COL_CALLED:
				typnam->name = "char";
				coldef->colname = "is_called";
				value[i - 1] = CharGetDatum('f');
				break;
150 151 152 153 154 155 156 157
		}
		stmt->tableElts = lappend(stmt->tableElts, coldef);
	}

	stmt->relname = seq->seqname;
	stmt->inhRelnames = NIL;
	stmt->constraints = NIL;

158
	DefineRelation(stmt, RELKIND_SEQUENCE);
159

160
	rel = heap_openr(seq->seqname, AccessExclusiveLock);
161

162
	tupDesc = RelationGetDescr(rel);
163 164 165 166 167

	Assert(RelationGetNumberOfBlocks(rel) == 0);
	buf = ReadBuffer(rel, P_NEW);

	if (!BufferIsValid(buf))
168
		elog(ERROR, "DefineSequence: ReadBuffer failed");
169 170 171 172 173 174 175 176 177 178 179 180

	page = (PageHeader) BufferGetPage(buf);

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

	/* Now - form & insert sequence tuple */
	tuple = heap_formtuple(tupDesc, value, null);
	heap_insert(rel, tuple);

	if (WriteBuffer(buf) == STATUS_ERROR)
181
		elog(ERROR, "DefineSequence: WriteBuffer failed");
182

183
	heap_close(rel, AccessExclusiveLock);
184 185 186
}


187 188
Datum
nextval(PG_FUNCTION_ARGS)
189
{
190 191
	text	   *seqin = PG_GETARG_TEXT_P(0);
	char	   *seqname = get_seq_name(seqin);
192 193
	SeqTable	elm;
	Buffer		buf;
194
	Form_pg_sequence seq;
195
	int32		incby,
196 197 198
				maxv,
				minv,
				cache;
199
	int32		result,
200 201
				next,
				rescnt = 0;
202

203
#ifndef NO_SECURITY
204
	if (pg_aclcheck(seqname, GetUserId(), ACL_WR) != ACLCHECK_OK)
205 206 207 208
		elog(ERROR, "%s.nextval: you don't have permissions to set sequence %s",
			 seqname, seqname);
#endif

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

212 213 214 215 216
	pfree(seqname);

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
		elm->last += elm->increment;
217
		PG_RETURN_INT32(elm->last);
218
	}
219

B
Bruce Momjian 已提交
220 221
	seq = read_info("nextval", elm, &buf);		/* lock page' buffer and
												 * read tuple */
222 223 224 225 226 227 228 229 230 231 232

	next = result = seq->last_value;
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
	cache = seq->cache_value;

	if (seq->is_called != 't')
		rescnt++;				/* last_value if not called */

	while (rescnt < cache)		/* try to fetch cache numbers */
233
	{
234 235 236 237 238

		/*
		 * Check MAXVALUE for ascending sequences and MINVALUE for
		 * descending sequences
		 */
239
		if (incby > 0)
240
		{
241
			/* ascending sequence */
242 243 244 245 246 247
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
					break;		/* stop caching */
				if (seq->is_cycled != 't')
248
					elog(ERROR, "%s.nextval: got MAXVALUE (%d)",
249 250 251 252 253 254 255 256
						 elm->name, maxv);
				next = minv;
			}
			else
				next += incby;
		}
		else
		{
257
			/* descending sequence */
258 259 260 261 262 263
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
					break;		/* stop caching */
				if (seq->is_cycled != 't')
264
					elog(ERROR, "%s.nextval: got MINVALUE (%d)",
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
						 elm->name, minv);
				next = maxv;
			}
			else
				next += incby;
		}
		rescnt++;				/* got result */
		if (rescnt == 1)		/* if it's first one - */
			result = next;		/* it's what to return */
	}

	/* save info in local cache */
	elm->last = result;			/* last returned number */
	elm->cached = next;			/* last cached number */

	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
	seq->is_called = 't';

V
Vadim B. Mikheev 已提交
284 285
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

286
	if (WriteBuffer(buf) == STATUS_ERROR)
287
		elog(ERROR, "%s.nextval: WriteBuffer failed", elm->name);
288

289
	PG_RETURN_INT32(result);
290 291
}

292 293
Datum
currval(PG_FUNCTION_ARGS)
294
{
295 296
	text	   *seqin = PG_GETARG_TEXT_P(0);
	char	   *seqname = get_seq_name(seqin);
297
	SeqTable	elm;
298 299 300
	int32		result;

#ifndef NO_SECURITY
301
	if (pg_aclcheck(seqname, GetUserId(), ACL_RD) != ACLCHECK_OK)
302 303 304
		elog(ERROR, "%s.currval: you don't have permissions to read sequence %s",
			 seqname, seqname);
#endif
305

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

	if (elm->increment == 0)	/* nextval/read_info were not called */
310 311
		elog(ERROR, "%s.currval is not yet defined in this session",
			 seqname);
312 313 314

	result = elm->last;

315
	pfree(seqname);
316

317
	PG_RETURN_INT32(result);
318 319
}

320 321
Datum
setval(PG_FUNCTION_ARGS)
M
 
Marc G. Fournier 已提交
322
{
323 324 325
	text	   *seqin = PG_GETARG_TEXT_P(0);
	int32		next = PG_GETARG_INT32(1);
	char	   *seqname = get_seq_name(seqin);
M
 
Marc G. Fournier 已提交
326
	SeqTable	elm;
327
	Buffer		buf;
328
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
329 330

#ifndef NO_SECURITY
331
	if (pg_aclcheck(seqname, GetUserId(), ACL_WR) != ACLCHECK_OK)
M
 
Marc G. Fournier 已提交
332 333 334 335
		elog(ERROR, "%s.setval: you don't have permissions to set sequence %s",
			 seqname, seqname);
#endif

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

341 342 343 344
	if (seq->cache_value != 1)
	{
		elog(ERROR, "%s.setval: can't set value of sequence %s, cache != 1",
			 seqname, seqname);
M
 
Marc G. Fournier 已提交
345 346
	}

347 348 349 350
	if ((next < seq->min_value) || (next > seq->max_value))
	{
		elog(ERROR, "%s.setval: value %d is of of bounds (%d,%d)",
			 seqname, next, seq->min_value, seq->max_value);
M
 
Marc G. Fournier 已提交
351 352 353 354 355 356 357 358 359 360
	}

	/* save info in local cache */
	elm->last = next;			/* last returned number */
	elm->cached = next;			/* last cached number */

	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
	seq->is_called = 't';

V
Vadim B. Mikheev 已提交
361 362
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

363
	if (WriteBuffer(buf) == STATUS_ERROR)
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
		elog(ERROR, "%s.setval: WriteBuffer failed", seqname);

	pfree(seqname);

	PG_RETURN_INT32(next);
}

/*
 * Given a 'text' parameter to a sequence function, extract the actual
 * sequence name.  We downcase the name if it's not double-quoted.
 *
 * This is a kluge, really --- should be able to write nextval(seqrel).
 */
static char *
get_seq_name(text *seqin)
{
380 381
	char	   *rawname = DatumGetCString(DirectFunctionCall1(textout,
													PointerGetDatum(seqin)));
382 383
	int			rawlen = strlen(rawname);
	char	   *seqname;
M
 
Marc G. Fournier 已提交
384

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
	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;
		/*
		 * It's important that this match the identifier downcasing code
		 * used by backend/parser/scan.l.
		 */
		for (; *rawname; rawname++)
		{
402 403
			if (isascii((int) *rawname) &&
				isupper((int) *rawname))
404 405 406 407
				*rawname = tolower(*rawname);
		}
	}
	return seqname;
M
 
Marc G. Fournier 已提交
408 409
}

410
static Form_pg_sequence
B
Bruce Momjian 已提交
411
read_info(char *caller, SeqTable elm, Buffer *buf)
412
{
B
Bruce Momjian 已提交
413 414 415
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
416
	sequence_magic *sm;
B
Bruce Momjian 已提交
417
	Form_pg_sequence seq;
418 419

	if (RelationGetNumberOfBlocks(elm->rel) != 1)
420
		elog(ERROR, "%s.%s: invalid number of blocks in sequence",
421 422 423 424
			 elm->name, caller);

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

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

429 430 431 432
	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
433
		elog(ERROR, "%s.%s: bad magic (%08X)", elm->name, caller, sm->magic);
434 435 436

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

439
	seq = (Form_pg_sequence) GETSTRUCT(&tuple);
440 441 442

	elm->increment = seq->increment_by;

443
	return seq;
444 445 446 447

}


448
static SeqTable
449
init_sequence(char *caller, char *name)
450
{
451
	SeqTable	elm,
452 453
				prev = (SeqTable) NULL;
	Relation	seqrel;
454

455 456
	/* Look to see if we already have a seqtable entry for name */
	for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next)
457 458 459
	{
		if (strcmp(elm->name, name) == 0)
			break;
460
		prev = elm;
461 462
	}

463 464 465
	/* 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;
466

467 468 469
	/* Else open and check it */
	seqrel = heap_openr(name, AccessShareLock);
	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
470
		elog(ERROR, "%s.%s: %s is not sequence !", name, caller, name);
471

472 473
	if (elm != (SeqTable) NULL)
	{
474 475 476

		/*
		 * We are using a seqtable entry left over from a previous xact;
477 478 479 480
		 * must check for relid change.
		 */
		elm->rel = seqrel;
		if (RelationGetRelid(seqrel) != elm->relid)
481 482
		{
			elog(NOTICE, "%s.%s: sequence was re-created",
483
				 name, caller);
484
			elm->relid = RelationGetRelid(seqrel);
485 486 487 488 489
			elm->cached = elm->last = elm->increment = 0;
		}
	}
	else
	{
490 491 492

		/*
		 * Time to make a new seqtable entry.  These entries live as long
493 494 495 496 497 498 499 500 501 502
		 * as the backend does, so we use plain malloc for them.
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
		elm->name = malloc(strlen(name) + 1);
		strcpy(elm->name, name);
		elm->rel = seqrel;
		elm->relid = RelationGetRelid(seqrel);
		elm->cached = elm->last = elm->increment = 0;
		elm->next = (SeqTable) NULL;

503 504 505
		if (seqtab == (SeqTable) NULL)
			seqtab = elm;
		else
506
			prev->next = elm;
507 508
	}

509
	return elm;
510 511 512 513
}


/*
B
Bruce Momjian 已提交
514
 * CloseSequences
515
 *				is calling by xact mgr at commit/abort.
516 517
 */
void
518
CloseSequences(void)
519
{
520 521
	SeqTable	elm;
	Relation	rel;
522

523
	for (elm = seqtab; elm != (SeqTable) NULL; elm = elm->next)
524
	{
525 526 527 528
		if (elm->rel != (Relation) NULL)		/* opened in current xact */
		{
			rel = elm->rel;
			elm->rel = (Relation) NULL;
529
			heap_close(rel, AccessShareLock);
530 531
		}
	}
532 533 534
}


535
static void
536
init_params(CreateSeqStmt *seq, Form_pg_sequence new)
537
{
538 539 540 541 542 543
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
	List	   *option;
544 545 546 547

	new->is_cycled = 'f';
	foreach(option, seq->options)
	{
548
		DefElem    *defel = (DefElem *) lfirst(option);
549 550 551 552 553 554 555 556 557 558 559 560 561 562

		if (!strcasecmp(defel->defname, "increment"))
			increment_by = defel;
		else if (!strcasecmp(defel->defname, "start"))
			last_value = defel;
		else if (!strcasecmp(defel->defname, "maxvalue"))
			max_value = defel;
		else if (!strcasecmp(defel->defname, "minvalue"))
			min_value = defel;
		else if (!strcasecmp(defel->defname, "cache"))
			cache_value = defel;
		else if (!strcasecmp(defel->defname, "cycle"))
		{
			if (defel->arg != (Node *) NULL)
563
				elog(ERROR, "DefineSequence: CYCLE ??");
564 565 566
			new->is_cycled = 't';
		}
		else
567
			elog(ERROR, "DefineSequence: option \"%s\" not recognized",
568 569 570 571 572 573
				 defel->defname);
	}

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

	if (max_value == (DefElem *) NULL)	/* MAXVALUE */
577
	{
578 579 580 581
		if (new->increment_by > 0)
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
		else
			new->max_value = -1;/* descending seq */
582
	}
583
	else
584
		new->max_value = get_param(max_value);
585

586
	if (min_value == (DefElem *) NULL)	/* MINVALUE */
587
	{
588 589 590 591
		if (new->increment_by > 0)
			new->min_value = 1; /* ascending seq */
		else
			new->min_value = SEQ_MINVALUE;		/* descending seq */
592
	}
593
	else
594 595 596
		new->min_value = get_param(min_value);

	if (new->min_value >= new->max_value)
597
		elog(ERROR, "DefineSequence: MINVALUE (%d) can't be >= MAXVALUE (%d)",
598 599 600
			 new->min_value, new->max_value);

	if (last_value == (DefElem *) NULL) /* START WITH */
601
	{
602 603 604 605
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
606
	}
607
	else
608 609 610
		new->last_value = get_param(last_value);

	if (new->last_value < new->min_value)
611
		elog(ERROR, "DefineSequence: START value (%d) can't be < MINVALUE (%d)",
612 613
			 new->last_value, new->min_value);
	if (new->last_value > new->max_value)
614
		elog(ERROR, "DefineSequence: START value (%d) can't be > MAXVALUE (%d)",
615 616 617 618 619
			 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)
620
		elog(ERROR, "DefineSequence: CACHE (%d) can't be <= 0",
621
			 new->cache_value);
622 623 624 625 626

}


static int
627
get_param(DefElem *def)
628
{
629
	if (def->arg == (Node *) NULL)
630
		elog(ERROR, "DefineSequence: \"%s\" value unspecified", def->defname);
631 632

	if (nodeTag(def->arg) == T_Integer)
633
		return intVal(def->arg);
634

635
	elog(ERROR, "DefineSequence: \"%s\" is to be integer", def->defname);
636
	return -1;
637
}