sequence.c 13.5 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5 6 7 8 9 10 11
 *
 *-------------------------------------------------------------------------
 */
#include <stdio.h>
#include <string.h>

#include <postgres.h>
M
 
Marc G. Fournier 已提交
12
#include <miscadmin.h>
13 14 15 16 17 18 19 20 21

#include <storage/bufmgr.h>
#include <storage/bufpage.h>
#include <storage/lmgr.h>
#include <access/heapam.h>
#include <nodes/parsenodes.h>
#include <commands/creatinh.h>
#include <commands/sequence.h>
#include <utils/builtins.h>
M
 
Marc G. Fournier 已提交
22
#include <utils/acl.h>
23

24
#define SEQ_MAGIC	  0x1717
25 26 27 28

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

29 30
typedef struct FormData_pg_sequence
{
31 32 33 34 35 36 37 38
	NameData	sequence_name;
	int4		last_value;
	int4		increment_by;
	int4		max_value;
	int4		min_value;
	int4		cache_value;
	char		is_cycled;
	char		is_called;
39
} FormData_pg_sequence;
40

41
typedef FormData_pg_sequence *Form_pg_sequence;
42 43 44

typedef struct sequence_magic
{
45
	uint32		magic;
46
} sequence_magic;
47

48 49
typedef struct SeqTableData
{
50 51 52 53 54 55
	char	   *name;
	Oid			relid;
	Relation	rel;
	int4		cached;
	int4		last;
	int4		increment;
56
	struct SeqTableData *next;
57
} SeqTableData;
58 59 60 61 62

typedef SeqTableData *SeqTable;

static SeqTable seqtab = NULL;

63
static SeqTable init_sequence(char *caller, char *name);
64 65
static Form_pg_sequence read_info(char *caller, SeqTable elm, Buffer *buf);
static void init_params(CreateSeqStmt *seq, Form_pg_sequence new);
66
static int	get_param(DefElem *def);
67 68

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

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

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

		switch (i)
		{
111 112 113
			case SEQ_COL_NAME:
				typnam->name = "name";
				coldef->colname = "sequence_name";
114 115
				namestrcpy(&name, seq->seqname);
				value[i - 1] = NameGetDatum(&name);
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 150 151
				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;
152 153 154 155 156 157 158 159
		}
		stmt->tableElts = lappend(stmt->tableElts, coldef);
	}

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

160
	DefineRelation(stmt, RELKIND_SEQUENCE);
161 162 163 164

	rel = heap_openr(seq->seqname);
	Assert(RelationIsValid(rel));

V
Vadim B. Mikheev 已提交
165
	LockRelation(rel, AccessExclusiveLock);
166

167
	tupDesc = RelationGetDescr(rel);
168 169 170 171 172

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

	if (!BufferIsValid(buf))
173
		elog(ERROR, "DefineSequence: ReadBuffer failed");
174 175 176 177 178 179 180 181 182 183 184 185

	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)
186
		elog(ERROR, "DefineSequence: WriteBuffer failed");
187

V
Vadim B. Mikheev 已提交
188
	UnlockRelation(rel, AccessExclusiveLock);
189 190 191
	heap_close(rel);

	return;
192 193 194 195 196

}


int4
197
nextval(struct varlena * seqin)
198
{
199 200 201
	char	   *seqname = textout(seqin);
	SeqTable	elm;
	Buffer		buf;
202
	Form_pg_sequence seq;
203 204 205 206 207 208 209
	int4		incby,
				maxv,
				minv,
				cache;
	int4		result,
				next,
				rescnt = 0;
210

V
Vadim B. Mikheev 已提交
211
	/* open and AccessShareLock sequence */
212 213 214 215 216 217
	elm = init_sequence("nextval", seqname);
	pfree(seqname);

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

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

	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 */
234
	{
235 236 237 238 239 240 241 242 243 244 245 246 247

		/*
		 * Check MAXVALUE for ascending sequences and MINVALUE for
		 * descending sequences
		 */
		if (incby > 0)			/* ascending sequence */
		{
			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 257 258 259 260 261 262 263
						 elm->name, maxv);
				next = minv;
			}
			else
				next += incby;
		}
		else
/* descending sequence */
		{
			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
	return result;
290

291 292 293 294
}


int4
295
currval(struct varlena * seqin)
296
{
297 298 299
	char	   *seqname = textout(seqin);
	SeqTable	elm;
	int4		result;
300

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

	if (elm->increment == 0)	/* nextval/read_info were not called */
306
		elog(ERROR, "%s.currval is not yet defined in this session", elm->name);
307 308 309

	result = elm->last;

310
	return result;
311

312 313
}

M
 
Marc G. Fournier 已提交
314 315 316
int4
setval(struct varlena * seqin, int4 next)
{
317
	char	   *seqname = textout(seqin);
M
 
Marc G. Fournier 已提交
318
	SeqTable	elm;
319
	Buffer		buf;
320
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
321 322 323 324 325 326 327

#ifndef NO_SECURITY
	if (pg_aclcheck(seqname, getpgusername(), ACL_WR) != ACLCHECK_OK)
		elog(ERROR, "%s.setval: you don't have permissions to set sequence %s",
			 seqname, seqname);
#endif

V
Vadim B. Mikheev 已提交
328
	/* open and AccessShareLock sequence */
329
	elm = init_sequence("setval", seqname);
V
Vadim B. Mikheev 已提交
330
	seq = read_info("setval", elm, &buf);		/* lock page' buffer and read
331
												 * tuple */
M
 
Marc G. Fournier 已提交
332

333 334 335 336
	if (seq->cache_value != 1)
	{
		elog(ERROR, "%s.setval: can't set value of sequence %s, cache != 1",
			 seqname, seqname);
M
 
Marc G. Fournier 已提交
337 338
	}

339 340 341 342
	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 已提交
343 344 345 346 347 348 349 350 351 352
	}

	/* 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 已提交
353 354
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);

355 356
	if (WriteBuffer(buf) == STATUS_ERROR)
		elog(ERROR, "%s.settval: WriteBuffer failed", seqname);
M
 
Marc G. Fournier 已提交
357

358
	return next;
M
 
Marc G. Fournier 已提交
359 360
}

361
static Form_pg_sequence
B
Bruce Momjian 已提交
362
read_info(char *caller, SeqTable elm, Buffer *buf)
363
{
V
Vadim B. Mikheev 已提交
364 365
	PageHeader		page;
	ItemId			lp;
366
	HeapTupleData	tuple;
367
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
368
	Form_pg_sequence	seq;
369 370

	if (RelationGetNumberOfBlocks(elm->rel) != 1)
371
		elog(ERROR, "%s.%s: invalid number of blocks in sequence",
372 373 374 375
			 elm->name, caller);

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

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

380 381 382 383
	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
384
		elog(ERROR, "%s.%s: bad magic (%08X)", elm->name, caller, sm->magic);
385 386 387

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

390
	seq = (Form_pg_sequence) GETSTRUCT(&tuple);
391 392 393

	elm->increment = seq->increment_by;

394
	return seq;
395 396 397 398

}


399
static SeqTable
400
init_sequence(char *caller, char *name)
401
{
402 403 404
	SeqTable	elm,
				priv = (SeqTable) NULL;
	SeqTable	temp;
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

	for (elm = seqtab; elm != (SeqTable) NULL;)
	{
		if (strcmp(elm->name, name) == 0)
			break;
		priv = elm;
		elm = elm->next;
	}

	if (elm == (SeqTable) NULL) /* not found */
	{
		temp = (SeqTable) malloc(sizeof(SeqTableData));
		temp->name = malloc(strlen(name) + 1);
		strcpy(temp->name, name);
		temp->rel = (Relation) NULL;
		temp->cached = temp->last = temp->increment = 0;
		temp->next = (SeqTable) NULL;
	}
	else
/* found */
	{
		if (elm->rel != (Relation) NULL)		/* already opened */
427
			return elm;
428 429 430 431 432 433
		temp = elm;
	}

	temp->rel = heap_openr(name);

	if (!RelationIsValid(temp->rel))
434
		elog(ERROR, "%s.%s: sequence does not exist", name, caller);
435

V
Vadim B. Mikheev 已提交
436
	LockRelation(temp->rel, AccessShareLock);
437 438

	if (temp->rel->rd_rel->relkind != RELKIND_SEQUENCE)
439
		elog(ERROR, "%s.%s: %s is not sequence !", name, caller, name);
440 441 442

	if (elm != (SeqTable) NULL) /* we opened sequence from our */
	{							/* SeqTable - check relid ! */
443
		if (RelationGetRelid(elm->rel) != elm->relid)
444 445 446 447
		{
			elog(NOTICE, "%s.%s: sequence was re-created",
				 name, caller, name);
			elm->cached = elm->last = elm->increment = 0;
448
			elm->relid = RelationGetRelid(elm->rel);
449 450 451 452 453
		}
	}
	else
	{
		elm = temp;
454
		elm->relid = RelationGetRelid(elm->rel);
455 456 457 458 459 460
		if (seqtab == (SeqTable) NULL)
			seqtab = elm;
		else
			priv->next = elm;
	}

461
	return elm;
462

463 464 465 466
}


/*
467
 * CloseSequences 
468
 *				is calling by xact mgr at commit/abort.
469 470
 */
void
471
CloseSequences(void)
472
{
473 474
	SeqTable	elm;
	Relation	rel;
475 476

	for (elm = seqtab; elm != (SeqTable) NULL;)
477
	{
478 479 480 481
		if (elm->rel != (Relation) NULL)		/* opened in current xact */
		{
			rel = elm->rel;
			elm->rel = (Relation) NULL;
V
Vadim B. Mikheev 已提交
482
			UnlockRelation(rel, AccessShareLock);
483 484 485 486 487 488 489
			heap_close(rel);
		}
		elm = elm->next;
	}

	return;

490 491 492
}


493
static void
494
init_params(CreateSeqStmt *seq, Form_pg_sequence new)
495
{
496 497 498 499 500 501
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
	List	   *option;
502 503 504 505

	new->is_cycled = 'f';
	foreach(option, seq->options)
	{
506
		DefElem    *defel = (DefElem *) lfirst(option);
507 508 509 510 511 512 513 514 515 516 517 518 519 520

		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)
521
				elog(ERROR, "DefineSequence: CYCLE ??");
522 523 524
			new->is_cycled = 't';
		}
		else
525
			elog(ERROR, "DefineSequence: option \"%s\" not recognized",
526 527 528 529 530 531
				 defel->defname);
	}

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

	if (max_value == (DefElem *) NULL)	/* MAXVALUE */
535
	{
536 537 538 539
		if (new->increment_by > 0)
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
		else
			new->max_value = -1;/* descending seq */
540
	}
541
	else
542
		new->max_value = get_param(max_value);
543

544
	if (min_value == (DefElem *) NULL)	/* MINVALUE */
545
	{
546 547 548 549
		if (new->increment_by > 0)
			new->min_value = 1; /* ascending seq */
		else
			new->min_value = SEQ_MINVALUE;		/* descending seq */
550
	}
551
	else
552 553 554
		new->min_value = get_param(min_value);

	if (new->min_value >= new->max_value)
555
		elog(ERROR, "DefineSequence: MINVALUE (%d) can't be >= MAXVALUE (%d)",
556 557 558
			 new->min_value, new->max_value);

	if (last_value == (DefElem *) NULL) /* START WITH */
559
	{
560 561 562 563
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
564
	}
565
	else
566 567 568
		new->last_value = get_param(last_value);

	if (new->last_value < new->min_value)
569
		elog(ERROR, "DefineSequence: START value (%d) can't be < MINVALUE (%d)",
570 571
			 new->last_value, new->min_value);
	if (new->last_value > new->max_value)
572
		elog(ERROR, "DefineSequence: START value (%d) can't be > MAXVALUE (%d)",
573 574 575 576 577
			 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)
578
		elog(ERROR, "DefineSequence: CACHE (%d) can't be <= 0",
579
			 new->cache_value);
580 581 582 583 584

}


static int
585
get_param(DefElem *def)
586
{
587
	if (def->arg == (Node *) NULL)
588
		elog(ERROR, "DefineSequence: \"%s\" value unspecified", def->defname);
589 590

	if (nodeTag(def->arg) == T_Integer)
591
		return intVal(def->arg);
592

593
	elog(ERROR, "DefineSequence: \"%s\" is to be integer", def->defname);
594
	return -1;
595
}