sequence.c 51.3 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * sequence.c
4
 *	  PostgreSQL sequences support code.
5
 *
6 7
 * Portions Copyright (c) 2005-2008, Greenplum inc.
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
8 9 10 11
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
12
 *	  $PostgreSQL: pgsql/src/backend/commands/sequence.c,v 1.143 2007/02/01 19:10:26 momjian Exp $
13
 *
14 15
 *-------------------------------------------------------------------------
 */
16
#include "postgres.h"
17

18
#include "access/heapam.h"
19 20
#include "access/transam.h"
#include "access/xact.h"
21
#include "catalog/catquery.h"
22
#include "catalog/dependency.h"
23
#include "catalog/heap.h"
24
#include "catalog/namespace.h"
25
#include "catalog/pg_type.h"
26
#include "commands/defrem.h"
27
#include "commands/sequence.h"
28
#include "commands/tablecmds.h"
B
Bruce Momjian 已提交
29
#include "miscadmin.h"
30
#include "storage/smgr.h"               /* RelationCloseSmgr -> smgrclose */
31
#include "nodes/makefuncs.h"
32
#include "utils/acl.h"
B
Bruce Momjian 已提交
33
#include "utils/builtins.h"
34
#include "utils/formatting.h"
35
#include "utils/lsyscache.h"
36
#include "utils/resowner.h"
37
#include "utils/syscache.h"
38

39 40 41 42 43 44 45 46 47 48
#include "cdb/cdbdisp.h"
#include "cdb/cdbsrlz.h"
#include "cdb/cdbvars.h"
#include "cdb/cdbmotion.h"
#include "cdb/ml_ipc.h"

#include "cdb/cdbpersistentfilesysobj.h"

#include "postmaster/seqserver.h"

49

V
Vadim B. Mikheev 已提交
50
/*
51
 * We don't want to log each fetching of a value from a sequence,
V
Vadim B. Mikheev 已提交
52 53 54
 * 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 已提交
55
#define SEQ_LOG_VALS	32
56

57 58 59 60 61
/*
 * The "special area" of a sequence's buffer page looks like this.
 */
#define SEQ_MAGIC	  0x1717

62 63
typedef struct sequence_magic
{
64
	uint32		magic;
65
} sequence_magic;
66

67 68 69 70 71 72
/*
 * We store a SeqTable item for every sequence we have touched in the current
 * session.  This is needed to hold onto nextval/currval state.  (We can't
 * rely on the relcache, since it's only, well, a cache, and may decide to
 * discard entries.)
 *
B
Bruce Momjian 已提交
73
 * XXX We use linear search to find pre-existing SeqTable entries.	This is
74 75 76
 * good when only a small number of sequences are touched in a session, but
 * would suck with many different sequences.  Perhaps use a hashtable someday.
 */
77 78
typedef struct SeqTableData
{
79 80 81 82 83 84 85
	struct SeqTableData *next;	/* link to next SeqTable object */
	Oid			relid;			/* pg_class OID of this sequence */
	TransactionId xid;			/* xact in which we last did a seq op */
	int64		last;			/* value last returned by nextval */
	int64		cached;			/* last value already cached for nextval */
	/* if last != cached, we have not used up all the cached values */
	int64		increment;		/* copy of sequence's increment field */
86
} SeqTableData;
87 88 89

typedef SeqTableData *SeqTable;

90
static SeqTable seqtab = NULL;	/* Head of list of SeqTable items */
91

92 93 94 95 96
/*
 * last_used_seq is updated by nextval() to point to the last used
 * sequence.
 */
static SeqTableData *last_used_seq = NULL;
97

98
static int64 nextval_internal(Oid relid);
99
static Relation open_share_lock(SeqTable seq);
100
static void init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel);
101
static Form_pg_sequence read_info(Relation rel, Buffer *buf);
102
static void init_params(List *options, bool isInit,
B
Bruce Momjian 已提交
103
			Form_pg_sequence new, List **owned_by);
104
static void do_setval(Oid relid, int64 next, bool iscalled);
105 106
static void process_owned_by(Relation seqrel, List *owned_by);

107 108 109 110 111 112 113 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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
static void
cdb_sequence_nextval(Relation   seqrel,
                     int64     *plast,
                     int64     *pcached,
                     int64     *pincrement,
                     bool      *seq_overflow);
static void
cdb_sequence_nextval_proxy(Relation seqrel,
                           int64   *plast,
                           int64   *pcached,
                           int64   *pincrement,
                           bool    *poverflow);

typedef struct SequencePersistentInfoCacheEntryKey
{
	RelFileNode				relFileNode;
} SequencePersistentInfoCacheEntryKey;

typedef struct SequencePersistentInfoCacheEntryData
{
	SequencePersistentInfoCacheEntryKey	key;

	ItemPointerData		persistentTid;

	int64				persistentSerialNum;

	DoubleLinks			lruLinks;

} SequencePersistentInfoCacheEntryData;
typedef SequencePersistentInfoCacheEntryData *SequencePersistentInfoCacheEntry;

static HTAB *sequencePersistentInfoCacheTable = NULL;

static DoublyLinkedHead	sequencePersistentInfoCacheLruListHead;

static int sequencePersistentInfoCacheLruCount = 0;

static int sequencePersistentInfoCacheLruLimit = 100;

static void
Sequence_PersistentInfoCacheTableInit(void)
{
	HASHCTL			info;
	int				hash_flags;

	/* Set key and entry sizes. */
	MemSet(&info, 0, sizeof(info));
	info.keysize = sizeof(SequencePersistentInfoCacheEntryKey);
	info.entrysize = sizeof(SequencePersistentInfoCacheEntryData);
	info.hash = tag_hash;

	hash_flags = (HASH_ELEM | HASH_FUNCTION);

	sequencePersistentInfoCacheTable = hash_create("Sequence Persistent Info", 10, &info, hash_flags);

	DoublyLinkedHead_Init(
				&sequencePersistentInfoCacheLruListHead);
}

static bool Sequence_CheckPersistentInfoCache(
	RelFileNode 		*relFileNode,

	ItemPointer			persistentTid,

	int64				*persistentSerialNum)
{
	SequencePersistentInfoCacheEntryKey	key;

	SequencePersistentInfoCacheEntry persistentInfoCacheEntry;

	bool found;

	if (sequencePersistentInfoCacheTable == NULL)
		Sequence_PersistentInfoCacheTableInit();

	MemSet(&key, 0, sizeof(SequencePersistentInfoCacheEntryKey));
	key.relFileNode = *relFileNode;

	persistentInfoCacheEntry = 
		(SequencePersistentInfoCacheEntry) 
						hash_search(sequencePersistentInfoCacheTable,
									(void *) &key,
									HASH_FIND,
									&found);
	if (!found)
		return false;
	
	*persistentTid = persistentInfoCacheEntry->persistentTid;
	*persistentSerialNum = persistentInfoCacheEntry->persistentSerialNum;

	/*
	 * LRU.
	 */
	DoubleLinks_Remove(
		offsetof(SequencePersistentInfoCacheEntryData, lruLinks),
		&sequencePersistentInfoCacheLruListHead,
		persistentInfoCacheEntry);

	DoublyLinkedHead_AddFirst(
		offsetof(SequencePersistentInfoCacheEntryData, lruLinks),
		&sequencePersistentInfoCacheLruListHead,
		persistentInfoCacheEntry);

	return true;	
}

static void Sequence_AddPersistentInfoCache(
	RelFileNode 		*relFileNode,

	ItemPointer			persistentTid,

	int64				persistentSerialNum)
{
	SequencePersistentInfoCacheEntryKey	key;

	SequencePersistentInfoCacheEntry persistentInfoCacheEntry;

	bool found;

	if (sequencePersistentInfoCacheTable == NULL)
		Sequence_PersistentInfoCacheTableInit();

	MemSet(&key, 0, sizeof(SequencePersistentInfoCacheEntryKey));
	key.relFileNode = *relFileNode;

	persistentInfoCacheEntry = 
		(SequencePersistentInfoCacheEntry) 
						hash_search(
								sequencePersistentInfoCacheTable,
								(void *) &key,
								HASH_ENTER,
								&found);
	Assert (!found);
	
	persistentInfoCacheEntry->persistentTid = *persistentTid;
	persistentInfoCacheEntry->persistentSerialNum = persistentSerialNum;

	DoubleLinks_Init(&persistentInfoCacheEntry->lruLinks);

	/*
	 * LRU.
	 */
	DoublyLinkedHead_AddFirst(
		offsetof(SequencePersistentInfoCacheEntryData, lruLinks),
		&sequencePersistentInfoCacheLruListHead,
		persistentInfoCacheEntry);

	sequencePersistentInfoCacheLruCount++;

	if (sequencePersistentInfoCacheLruCount > sequencePersistentInfoCacheLruLimit)
	{
		SequencePersistentInfoCacheEntry lastPersistentInfoCacheEntry;

		lastPersistentInfoCacheEntry = 
			(SequencePersistentInfoCacheEntry) 
							DoublyLinkedHead_Last(
								offsetof(SequencePersistentInfoCacheEntryData, lruLinks),
								&sequencePersistentInfoCacheLruListHead);
		Assert(lastPersistentInfoCacheEntry != NULL);
		
		DoubleLinks_Remove(
			offsetof(SequencePersistentInfoCacheEntryData, lruLinks),
			&sequencePersistentInfoCacheLruListHead,
			lastPersistentInfoCacheEntry);
		
		if (Debug_persistent_print)
			elog(Persistent_DebugPrintLevel(), 
				 "Removed cached persistent information for sequence %u/%u/%u -- serial number " INT64_FORMAT ", TID %s",
				 lastPersistentInfoCacheEntry->key.relFileNode.spcNode,
				 lastPersistentInfoCacheEntry->key.relFileNode.dbNode,
				 lastPersistentInfoCacheEntry->key.relFileNode.relNode,
				 lastPersistentInfoCacheEntry->persistentSerialNum,
				 ItemPointerToString(&lastPersistentInfoCacheEntry->persistentTid));

		hash_search(
				sequencePersistentInfoCacheTable, 
				(void *) &lastPersistentInfoCacheEntry->key, 
				HASH_REMOVE, 
				NULL);
		
		sequencePersistentInfoCacheLruCount--;
	}
}


static void
Sequence_FetchGpRelationNodeForXLog(Relation rel)
{
	if (rel->rd_segfile0_relationnodeinfo.isPresent)
		return;

	/*
	 * For better performance, we cache the persistent information
	 * for sequences with upper bound and use LRU...
	 */
	if (Sequence_CheckPersistentInfoCache(
								&rel->rd_node,
								&rel->rd_segfile0_relationnodeinfo.persistentTid,
								&rel->rd_segfile0_relationnodeinfo.persistentSerialNum))
	{
		if (Debug_persistent_print)
			elog(Persistent_DebugPrintLevel(), 
				 "Found cached persistent information for sequence %u/%u/%u -- serial number " INT64_FORMAT ", TID %s",
				 rel->rd_node.spcNode,
				 rel->rd_node.dbNode,
				 rel->rd_node.relNode,
				 rel->rd_segfile0_relationnodeinfo.persistentSerialNum,
				 ItemPointerToString(&rel->rd_segfile0_relationnodeinfo.persistentTid));
	} 
	else 
	{
		if (!PersistentFileSysObj_ScanForRelation(
												&rel->rd_node,
												/* segmentFileNum */ 0,
												&rel->rd_segfile0_relationnodeinfo.persistentTid,
												&rel->rd_segfile0_relationnodeinfo.persistentSerialNum))
		{
			elog(ERROR, "Cound not find persistent information for sequence %u/%u/%u",
			     rel->rd_node.spcNode,
			     rel->rd_node.dbNode,
			     rel->rd_node.relNode);
		}

		Sequence_AddPersistentInfoCache(
								&rel->rd_node,
								&rel->rd_segfile0_relationnodeinfo.persistentTid,
								rel->rd_segfile0_relationnodeinfo.persistentSerialNum);

		if (Debug_persistent_print)
			elog(Persistent_DebugPrintLevel(), 
				 "Add cached persistent information for sequence %u/%u/%u -- serial number " INT64_FORMAT ", TID %s",
				 rel->rd_node.spcNode,
				 rel->rd_node.dbNode,
				 rel->rd_node.relNode,
				 rel->rd_segfile0_relationnodeinfo.persistentSerialNum,
				 ItemPointerToString(&rel->rd_segfile0_relationnodeinfo.persistentTid));
	}

	if (Debug_check_for_invalid_persistent_tid &&
		!Persistent_BeforePersistenceWork() &&
		PersistentStore_IsZeroTid(&rel->rd_segfile0_relationnodeinfo.persistentTid))
	{	
		elog(ERROR, 
			 "Sequence_FetchGpRelationNodeForXLog has invalid TID (0,0) for relation %u/%u/%u '%s', serial number " INT64_FORMAT,
			 rel->rd_node.spcNode,
			 rel->rd_node.dbNode,
			 rel->rd_node.relNode,
			 NameStr(rel->rd_rel->relname),
			 rel->rd_segfile0_relationnodeinfo.persistentSerialNum);
	}

	rel->rd_segfile0_relationnodeinfo.isPresent = true;
}
360 361

/*
B
Bruce Momjian 已提交
362
 * DefineSequence
363
 *				Creates a new sequence relation
364 365
 */
void
366
DefineSequence(CreateSeqStmt *seq)
367
{
368 369
	MIRROREDLOCK_BUFMGR_DECLARE;

370
	FormData_pg_sequence new;
371
	List	   *owned_by;
372
	CreateStmt *stmt = makeNode(CreateStmt);
373
	Oid			seqoid;
374 375 376
	Relation	rel;
	Buffer		buf;
	PageHeader	page;
377
	sequence_magic *sm;
378 379 380
	HeapTuple	tuple;
	TupleDesc	tupDesc;
	Datum		value[SEQ_COL_LASTCOL];
381
	bool		null[SEQ_COL_LASTCOL];
382
	int			i;
383
	NameData	name;
384

385 386
	bool shouldDispatch =  Gp_role == GP_ROLE_DISPATCH && !IsBootstrapProcessingMode();

387
	/* Check and set all option values */
388
	init_params(seq->options, true, &new, &owned_by);
389 390

	/*
391
	 * Create relation (and fill *null & *value)
392
	 */
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
	stmt->oidInfo.relOid = 0;
	stmt->oidInfo.comptypeOid = 0;
	stmt->oidInfo.toastOid = 0;
	stmt->oidInfo.toastIndexOid = 0;
	stmt->oidInfo.aosegOid = 0;
	stmt->oidInfo.aosegIndexOid = 0;
	stmt->oidInfo.aoblkdirOid = 0;
	stmt->oidInfo.aoblkdirIndexOid = 0;
	stmt->oidInfo.aovisimapOid = 0;
	stmt->oidInfo.aovisimapIndexOid = 0;

	if (shouldDispatch)
	{

			/* stmt->relOid = newOid(); */
	}
	else if (Gp_role == GP_ROLE_EXECUTE)
	{

			stmt->oidInfo.relOid = seq->relOid;

	}
415 416
	stmt->tableElts = NIL;
	for (i = SEQ_COL_FIRSTCOL; i <= SEQ_COL_LASTCOL; i++)
417
	{
418
		ColumnDef  *coldef = makeNode(ColumnDef);
419

420 421
		coldef->inhcount = 0;
		coldef->is_local = true;
422
		coldef->is_not_null = true;
423 424
		coldef->raw_default = NULL;
		coldef->cooked_default = NULL;
425 426
		coldef->constraints = NIL;

427
		null[i - 1] = false;
428 429 430

		switch (i)
		{
431
			case SEQ_COL_NAME:
432
				coldef->typname = makeTypeNameFromOid(NAMEOID, -1);
433
				coldef->colname = "sequence_name";
434
				namestrcpy(&name, seq->sequence->relname);
435
				value[i - 1] = NameGetDatum(&name);
436 437
				break;
			case SEQ_COL_LASTVAL:
438
				coldef->typname = makeTypeNameFromOid(INT8OID, -1);
439
				coldef->colname = "last_value";
440
				value[i - 1] = Int64GetDatumFast(new.last_value);
441 442
				break;
			case SEQ_COL_INCBY:
443
				coldef->typname = makeTypeNameFromOid(INT8OID, -1);
444
				coldef->colname = "increment_by";
445
				value[i - 1] = Int64GetDatumFast(new.increment_by);
446 447
				break;
			case SEQ_COL_MAXVALUE:
448
				coldef->typname = makeTypeNameFromOid(INT8OID, -1);
449
				coldef->colname = "max_value";
450
				value[i - 1] = Int64GetDatumFast(new.max_value);
451 452
				break;
			case SEQ_COL_MINVALUE:
453
				coldef->typname = makeTypeNameFromOid(INT8OID, -1);
454
				coldef->colname = "min_value";
455
				value[i - 1] = Int64GetDatumFast(new.min_value);
456 457
				break;
			case SEQ_COL_CACHE:
458
				coldef->typname = makeTypeNameFromOid(INT8OID, -1);
459
				coldef->colname = "cache_value";
460
				value[i - 1] = Int64GetDatumFast(new.cache_value);
461
				break;
V
Vadim B. Mikheev 已提交
462
			case SEQ_COL_LOG:
463
				coldef->typname = makeTypeNameFromOid(INT8OID, -1);
V
Vadim B. Mikheev 已提交
464
				coldef->colname = "log_cnt";
465
				value[i - 1] = Int64GetDatum((int64) 1);
V
Vadim B. Mikheev 已提交
466
				break;
467
			case SEQ_COL_CYCLE:
468
				coldef->typname = makeTypeNameFromOid(BOOLOID, -1);
469
				coldef->colname = "is_cycled";
470
				value[i - 1] = BoolGetDatum(new.is_cycled);
471 472
				break;
			case SEQ_COL_CALLED:
473
				coldef->typname = makeTypeNameFromOid(BOOLOID, -1);
474
				coldef->colname = "is_called";
475
				value[i - 1] = BoolGetDatum(false);
476
				break;
477 478 479 480
		}
		stmt->tableElts = lappend(stmt->tableElts, coldef);
	}

481 482
	stmt->relation = seq->sequence;
	stmt->inhRelations = NIL;
483
	stmt->constraints = NIL;
484 485
	stmt->inhOids = NIL;
	stmt->parentOidCount = 0;
B
Bruce Momjian 已提交
486
	stmt->options = list_make1(defWithOids(false));
487
	stmt->oncommit = ONCOMMIT_NOOP;
488
	stmt->tablespacename = NULL;
489 490 491
	stmt->relKind = RELKIND_SEQUENCE;
	stmt->oidInfo.comptypeOid = seq->comptypeOid;
	stmt->ownerid = GetUserId();
492

493
	seqoid = DefineRelation(stmt, RELKIND_SEQUENCE, RELSTORAGE_HEAP);
494

495 496 497 498 499 500 501 502
	/*
	 * Open and lock the new sequence.  (This lock is redundant; an
	 * AccessExclusiveLock was acquired above by DefineRelation and
	 * won't be released until end of transaction.)
	 *
	 * CDB: Acquire lock on qDisp before dispatching to qExecs, so
	 * qDisp can detect and resolve any deadlocks.
	 */
503
	rel = heap_open(seqoid, AccessExclusiveLock);
504
	tupDesc = RelationGetDescr(rel);
505

506 507
	stmt->oidInfo.relOid = seq->relOid = seqoid;

508 509
	/* Initialize first page of relation with special magic number */

510 511 512
	// -------- MirroredLock ----------
	MIRROREDLOCK_BUFMGR_LOCK;
	
513
	buf = ReadBuffer(rel, P_NEW);
514 515
	Assert(BufferGetBlockNumber(buf) == 0);

516 517
	page = (PageHeader) BufferGetPage(buf);

518 519
	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);

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

524 525 526 527 528
	LockBuffer(buf, BUFFER_LOCK_UNLOCK);
	
	MIRROREDLOCK_BUFMGR_UNLOCK;
	// -------- MirroredLock ----------
	
529 530 531
	/* hack: ensure heap_insert will insert on the just-created page */
	rel->rd_targblock = 0;

532
	/* Now form & insert sequence tuple */
533
	tuple = heap_form_tuple(tupDesc, value, null);
534
	simple_heap_insert(rel, tuple);
535

536 537
	Assert(ItemPointerGetOffsetNumber(&(tuple->t_self)) == FirstOffsetNumber);

538 539 540 541
	// Fetch gp_persistent_relation_node information that will be added to XLOG record.
	Assert(rel != NULL);
	Sequence_FetchGpRelationNodeForXLog(rel);

542
	/*
543 544
	 * Two special hacks here:
	 *
545 546
	 * 1. Since VACUUM does not process sequences, we have to force the tuple
	 * to have xmin = FrozenTransactionId now.	Otherwise it would become
B
Bruce Momjian 已提交
547
	 * invisible to SELECTs after 2G transactions.	It is okay to do this
548 549 550
	 * because if the current transaction aborts, no other xact will ever
	 * examine the sequence tuple anyway.
	 *
B
Bruce Momjian 已提交
551 552 553 554 555
	 * 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 :-(
556
	 */
557 558 559 560

	// -------- MirroredLock ----------
	MIRROREDLOCK_BUFMGR_LOCK;

561
	LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
562

563
	START_CRIT_SECTION();
564 565 566

	{
		/*
B
Bruce Momjian 已提交
567
		 * Note that the "tuple" structure is still just a local tuple record
568
		 * created by heap_form_tuple; its t_data pointer doesn't point at the
B
Bruce Momjian 已提交
569 570 571
		 * 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.
572 573 574 575 576 577 578
		 */
		ItemId		itemId;
		Item		item;

		itemId = PageGetItemId((Page) page, FirstOffsetNumber);
		item = PageGetItem((Page) page, itemId);

579
		HeapTupleHeaderSetXmin((HeapTupleHeader) item, FrozenTransactionId);
580 581
		((HeapTupleHeader) item)->t_infomask |= HEAP_XMIN_COMMITTED;

582
		HeapTupleHeaderSetXmin(tuple->t_data, FrozenTransactionId);
583 584 585
		tuple->t_data->t_infomask |= HEAP_XMIN_COMMITTED;
	}

586 587
	MarkBufferDirty(buf);

588 589
	/* XLOG stuff */
	if (!rel->rd_istemp)
590
	{
591 592 593 594
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];
		Form_pg_sequence newseq = (Form_pg_sequence) GETSTRUCT(tuple);
595 596

		/* We do not log first nextval call, so "advance" sequence here */
597
		/* Note we are scribbling on local tuple, not the disk buffer */
598
		newseq->is_called = true;
599 600 601
		newseq->log_cnt = 0;

		xlrec.node = rel->rd_node;
602 603 604
		xlrec.persistentTid = rel->rd_segfile0_relationnodeinfo.persistentTid;
		xlrec.persistentSerialNum = rel->rd_segfile0_relationnodeinfo.persistentSerialNum;

605 606
		rdata[0].data = (char *) &xlrec;
		rdata[0].len = sizeof(xl_seq_rec);
607
		rdata[0].buffer = InvalidBuffer;
608 609
		rdata[0].next = &(rdata[1]);

610
		rdata[1].data = (char *) tuple->t_data;
611
		rdata[1].len = tuple->t_len;
612
		rdata[1].buffer = InvalidBuffer;
613 614 615 616 617
		rdata[1].next = NULL;

		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);

		PageSetLSN(page, recptr);
618
		PageSetTLI(page, ThisTimeLineID);
619
	}
620

621
	END_CRIT_SECTION();
622

623 624
	UnlockReleaseBuffer(buf);

625 626 627
	MIRROREDLOCK_BUFMGR_UNLOCK;
	// -------- MirroredLock ----------

628 629 630 631
	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(rel, owned_by);

632
	heap_close(rel, NoLock);
633 634 635 636 637 638 639 640

	
	/* Dispatch to segments */
	if (shouldDispatch)
	{
		seq->comptypeOid = stmt->oidInfo.comptypeOid;
		CdbDispatchUtilityStatement((Node *)seq, "DefineSequence");
	}
641 642
}

B
Bruce Momjian 已提交
643 644 645
/*
 * AlterSequence
 *
646
 * Modify the definition of a sequence relation
B
Bruce Momjian 已提交
647 648
 */
void
649
AlterSequence(AlterSeqStmt *stmt)
B
Bruce Momjian 已提交
650
{
651 652
	MIRROREDLOCK_BUFMGR_DECLARE;

653
	Oid			relid;
B
Bruce Momjian 已提交
654 655 656 657 658 659
	SeqTable	elm;
	Relation	seqrel;
	Buffer		buf;
	Page		page;
	Form_pg_sequence seq;
	FormData_pg_sequence new;
660
	List	   *owned_by;
661 662 663 664 665
	int64		save_increment;
	bool		bSeqIsTemp	   = false;
	int			numopts	   = 0;
	char	   *alter_subtype = "";		/* metadata tracking: kind of
										   redundant to say "role" */
B
Bruce Momjian 已提交
666 667

	/* open and AccessShareLock sequence */
668 669
	relid = RangeVarGetRelid(stmt->sequence, false);
	init_sequence(relid, &elm, &seqrel);
B
Bruce Momjian 已提交
670

671
	/* allow ALTER to sequence owner only */
B
Bruce Momjian 已提交
672
	if (!pg_class_ownercheck(elm->relid, GetUserId()))
673 674
		aclcheck_error(ACLCHECK_NOT_OWNER, ACL_KIND_CLASS,
					   stmt->sequence->relname);
B
Bruce Momjian 已提交
675

676 677 678
	/* hack to keep ALTER SEQUENCE OWNED BY from changing currval state */
	save_increment = elm->increment;

B
Bruce Momjian 已提交
679
	/* lock page' buffer and read tuple into new sequence structure */
680 681 682 683 684 685
	
	// -------- MirroredLock ----------
	MIRROREDLOCK_BUFMGR_LOCK;
	
	seq = read_info(seqrel, &buf);
	elm->increment = seq->increment_by;
B
Bruce Momjian 已提交
686 687
	page = BufferGetPage(buf);

688 689
	/* Copy old values of options into workspace */
	memcpy(&new, seq, sizeof(FormData_pg_sequence));
B
Bruce Momjian 已提交
690

691
	/* Check and set new values */
692
	init_params(stmt->options, false, &new, &owned_by);
B
Bruce Momjian 已提交
693

694
	/* Now okay to update the on-disk tuple */
695
	memcpy(seq, &new, sizeof(FormData_pg_sequence));
B
Bruce Momjian 已提交
696

697 698 699 700 701 702 703 704 705 706
	if (owned_by)
	{
		/* Restore previous state of elm (assume nothing else changes) */
		elm->increment = save_increment;
	}
	else
	{
		/* Clear local cache so that we don't think we have cached numbers */
		elm->last = new.last_value; /* last returned number */
		elm->cached = new.last_value;	/* last cached number (forget cached
B
Bruce Momjian 已提交
707
										 * values) */
708 709 710 711 712
	}

	// Fetch gp_persistent_relation_node information that will be added to XLOG record.
	Assert(seqrel != NULL);
	Sequence_FetchGpRelationNodeForXLog(seqrel);
713

B
Bruce Momjian 已提交
714 715
	START_CRIT_SECTION();

716 717
	MarkBufferDirty(buf);

B
Bruce Momjian 已提交
718
	/* XLOG stuff */
719 720 721 722

	bSeqIsTemp = seqrel->rd_istemp;

	if (!bSeqIsTemp)
B
Bruce Momjian 已提交
723 724 725 726 727 728
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
		XLogRecData rdata[2];

		xlrec.node = seqrel->rd_node;
729 730 731
		xlrec.persistentTid = seqrel->rd_segfile0_relationnodeinfo.persistentTid;
		xlrec.persistentSerialNum = seqrel->rd_segfile0_relationnodeinfo.persistentSerialNum;

B
Bruce Momjian 已提交
732 733
		rdata[0].data = (char *) &xlrec;
		rdata[0].len = sizeof(xl_seq_rec);
734
		rdata[0].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
735 736 737 738 739
		rdata[0].next = &(rdata[1]);

		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
740
		rdata[1].buffer = InvalidBuffer;
B
Bruce Momjian 已提交
741 742 743 744 745
		rdata[1].next = NULL;

		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);

		PageSetLSN(page, recptr);
746
		PageSetTLI(page, ThisTimeLineID);
B
Bruce Momjian 已提交
747 748 749 750
	}

	END_CRIT_SECTION();

751
	UnlockReleaseBuffer(buf);
B
Bruce Momjian 已提交
752

753 754 755
	MIRROREDLOCK_BUFMGR_UNLOCK;
	// -------- MirroredLock ----------

756 757 758 759
	/* process OWNED BY if given */
	if (owned_by)
		process_owned_by(seqrel, owned_by);

B
Bruce Momjian 已提交
760
	relation_close(seqrel, NoLock);
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806

	numopts = list_length(stmt->options);

	if (numopts > 1)
	{
		char allopts[NAMEDATALEN];

		sprintf(allopts, "%d OPTIONS", numopts);

		alter_subtype = pstrdup(allopts);
	}
	else if (0 == numopts)
	{
		alter_subtype = "0 OPTIONS";
	}
	else if ((Gp_role == GP_ROLE_DISPATCH) && (!bSeqIsTemp))
	{
		ListCell		*option = list_head(stmt->options);
		DefElem			*defel	= (DefElem *) lfirst(option);
		char			*tempo	= NULL;

		alter_subtype = defel->defname;
		if (0 == strcmp(alter_subtype, "owned_by"))
			alter_subtype = "OWNED BY";

		tempo = str_toupper(alter_subtype, strlen(alter_subtype));

		alter_subtype = tempo;

	}

	if (Gp_role == GP_ROLE_DISPATCH)
	{
		CdbDispatchUtilityStatement((Node *)stmt, "AlterSequence");

		if (!bSeqIsTemp)
		{
			/* MPP-6929: metadata tracking */
			MetaTrackUpdObject(RelationRelationId,
							   relid,
							   GetUserId(),
							   "ALTER", alter_subtype
					);
		}

	}
B
Bruce Momjian 已提交
807 808
}

809

810 811 812 813 814
/*
 * Note: nextval with a text argument is no longer exported as a pg_proc
 * entry, but we keep it around to ease porting of C code that may have
 * called the function directly.
 */
815 816
Datum
nextval(PG_FUNCTION_ARGS)
817
{
818
	text	   *seqin = PG_GETARG_TEXT_P(0);
819
	RangeVar   *sequence;
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
	Oid			relid;

	sequence = makeRangeVarFromNameList(textToQualifiedNameList(seqin));
	relid = RangeVarGetRelid(sequence, false);

	PG_RETURN_INT64(nextval_internal(relid));
}

Datum
nextval_oid(PG_FUNCTION_ARGS)
{
	Oid			relid = PG_GETARG_OID(0);

	PG_RETURN_INT64(nextval_internal(relid));
}

static int64
nextval_internal(Oid relid)
{
839
	SeqTable	elm;
840
	Relation	seqrel;
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
	bool is_overflow = false;

	/* open and AccessShareLock sequence */
	init_sequence(relid, &elm, &seqrel);

	if (elm->last != elm->cached)		/* some numbers were cached */
	{
		last_used_seq = elm;
		elm->last += elm->increment;
		relation_close(seqrel, NoLock);
		return elm->last;
	}

	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for sequence %s",
						RelationGetRelationName(seqrel))));

    /* Update the sequence object. */
    if (Gp_role == GP_ROLE_EXECUTE)
        cdb_sequence_nextval_proxy(seqrel,
                                   &elm->last,
                                   &elm->cached,
                                   &elm->increment,
                                   &is_overflow);
    else
        cdb_sequence_nextval(seqrel,
                             &elm->last,
                             &elm->cached,
                             &elm->increment,
                             &is_overflow);
	last_used_seq = elm;

875 876 877 878 879 880 881 882 883 884 885 886
        if(is_overflow)
        {
                relation_close(seqrel, NoLock);

                ereport(ERROR,
                        (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                        errmsg("nextval: reached %s value of sequence \"%s\" (" INT64_FORMAT ")",
                        elm->increment>0 ? "maximum":"minimum",
                        RelationGetRelationName(seqrel), elm->last)));
        }

	relation_close(seqrel, NoLock);
887 888 889 890 891 892 893 894 895 896 897 898 899
	return elm->last;
}


void
cdb_sequence_nextval(Relation   seqrel,
                     int64     *plast,
                     int64     *pcached,
                     int64     *pincrement,
                     bool      *poverflow)
{
	MIRROREDLOCK_BUFMGR_DECLARE;

900
	Buffer		buf;
901
	Page		page;
902
	Form_pg_sequence seq;
903
	int64		incby,
904 905
				maxv,
				minv,
V
Vadim B. Mikheev 已提交
906 907 908 909
				cache,
				log,
				fetch,
				last;
910
	int64		result,
911 912
				next,
				rescnt = 0;
913
	bool 		have_overflow = false;
V
Vadim B. Mikheev 已提交
914
	bool		logit = false;
915

916
	/* lock page' buffer and read tuple */
917 918 919 920 921
	
	// -------- MirroredLock ----------
	MIRROREDLOCK_BUFMGR_LOCK;
	
	seq = read_info(seqrel, &buf);
922
	page = BufferGetPage(buf);
923

V
Vadim B. Mikheev 已提交
924
	last = next = result = seq->last_value;
925 926 927
	incby = seq->increment_by;
	maxv = seq->max_value;
	minv = seq->min_value;
V
Vadim B. Mikheev 已提交
928 929
	fetch = cache = seq->cache_value;
	log = seq->log_cnt;
930

931
	if (!seq->is_called)
V
Vadim B. Mikheev 已提交
932
	{
933
		rescnt++;				/* last_value if not called */
V
Vadim B. Mikheev 已提交
934 935 936
		fetch--;
		log--;
	}
937

938
	/*
B
Bruce Momjian 已提交
939 940 941
	 * 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.)
942
	 *
943 944 945 946
	 * 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.
947
	 */
V
Vadim B. Mikheev 已提交
948 949
	if (log < fetch)
	{
950 951
		/* forced log to satisfy local demand for values */
		fetch = log = fetch + SEQ_LOG_VALS;
V
Vadim B. Mikheev 已提交
952 953
		logit = true;
	}
954 955 956 957 958 959 960 961 962 963 964
	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 已提交
965

B
Bruce Momjian 已提交
966
	while (fetch)				/* try to fetch cache [+ log ] numbers */
967
	{
968
		/*
B
Bruce Momjian 已提交
969 970
		 * Check MAXVALUE for ascending sequences and MINVALUE for descending
		 * sequences
971
		 */
972
		if (incby > 0)
973
		{
974
			/* ascending sequence */
975 976 977 978
			if ((maxv >= 0 && next > maxv - incby) ||
				(maxv < 0 && next + incby > maxv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
979
					break;		/* stop fetching */
980
				if (!seq->is_cycled)
981
				{
982 983 984 985 986
					have_overflow = true;
				}
				else
				{
					next = minv;
987
				}
988 989 990 991 992 993
			}
			else
				next += incby;
		}
		else
		{
994
			/* descending sequence */
995 996 997 998
			if ((minv < 0 && next < minv - incby) ||
				(minv >= 0 && next + incby < minv))
			{
				if (rescnt > 0)
V
Vadim B. Mikheev 已提交
999
					break;		/* stop fetching */
1000
				if (!seq->is_cycled)
1001
				{
1002 1003 1004 1005 1006
					have_overflow = true;
				}
				else
				{
					next = maxv;
1007
				}
1008 1009 1010 1011
			}
			else
				next += incby;
		}
V
Vadim B. Mikheev 已提交
1012 1013 1014 1015 1016 1017
		fetch--;
		if (rescnt < cache)
		{
			log--;
			rescnt++;
			last = next;
B
Bruce Momjian 已提交
1018 1019
			if (rescnt == 1)	/* if it's first result - */
				result = next;	/* it's what to return */
V
Vadim B. Mikheev 已提交
1020
		}
1021 1022
	}

1023 1024 1025
	log -= fetch;				/* adjust for any unfetched numbers */
	Assert(log >= 0);

1026 1027 1028 1029 1030
    /* set results for caller */
	*poverflow = have_overflow; /* has the sequence overflown */
    *plast = result;            /* last returned number */
    *pcached = last;            /* last fetched number */
	*pincrement = incby;
V
Vadim B. Mikheev 已提交
1031

1032 1033 1034
	// Fetch gp_persistent_relation_node information that will be added to XLOG record.
	Assert(seqrel != NULL);
	Sequence_FetchGpRelationNodeForXLog(seqrel);
1035

1036
	START_CRIT_SECTION();
1037

1038 1039
	MarkBufferDirty(buf);

1040 1041
	/* XLOG stuff */
	if (logit && !seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
1042 1043 1044
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
1045
		XLogRecData rdata[2];
V
Vadim B. Mikheev 已提交
1046

1047
		xlrec.node = seqrel->rd_node;
1048 1049 1050
		xlrec.persistentTid = seqrel->rd_segfile0_relationnodeinfo.persistentTid;
		xlrec.persistentSerialNum = seqrel->rd_segfile0_relationnodeinfo.persistentSerialNum;

B
Bruce Momjian 已提交
1051
		rdata[0].data = (char *) &xlrec;
1052
		rdata[0].len = sizeof(xl_seq_rec);
1053
		rdata[0].buffer = InvalidBuffer;
1054 1055
		rdata[0].next = &(rdata[1]);

1056
		/* set values that will be saved in xlog */
1057
		seq->last_value = next;
1058
		seq->is_called = true;
1059
		seq->log_cnt = 0;
1060

B
Bruce Momjian 已提交
1061 1062 1063
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
1064
		rdata[1].buffer = InvalidBuffer;
1065 1066
		rdata[1].next = NULL;

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

1069
		PageSetLSN(page, recptr);
1070
		PageSetTLI(page, ThisTimeLineID);
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083

		/* need to update where we've inserted to into shmem so that the QD can flush it
		 * when necessary
		 */
		LWLockAcquire(SeqServerControlLock, LW_EXCLUSIVE);

		if (XLByteLT(seqServerCtl->lastXlogEntry, recptr))
		{
			seqServerCtl->lastXlogEntry.xlogid = recptr.xlogid;
			seqServerCtl->lastXlogEntry.xrecoff = recptr.xrecoff;
		}

		LWLockRelease(SeqServerControlLock);
V
Vadim B. Mikheev 已提交
1084
	}
1085

1086
	/* update on-disk data */
V
Vadim B. Mikheev 已提交
1087
	seq->last_value = last;		/* last fetched number */
1088
	seq->is_called = true;
V
Vadim B. Mikheev 已提交
1089
	seq->log_cnt = log;			/* how much is logged */
1090

1091
	END_CRIT_SECTION();
1092

1093
	UnlockReleaseBuffer(buf);
1094 1095 1096 1097 1098
	
	MIRROREDLOCK_BUFMGR_UNLOCK;
	// -------- MirroredLock ----------
	
}                               /* cdb_sequence_nextval */
1099

1100

1101
Datum
1102
currval_oid(PG_FUNCTION_ARGS)
1103
{
1104 1105
	Oid			relid = PG_GETARG_OID(0);
	int64		result;
1106
	SeqTable	elm;
1107
	Relation	seqrel;
1108

1109 1110 1111 1112 1113 1114 1115 1116
	/* For now, strictly forbidden on MPP. */
	if (Gp_role == GP_ROLE_DISPATCH || Gp_role == GP_ROLE_EXECUTE)
	{
		ereport(ERROR,
				(errcode(ERRCODE_GP_FEATURE_NOT_SUPPORTED),
				 errmsg("currval() not supported")));
	}

V
Vadim B. Mikheev 已提交
1117
	/* open and AccessShareLock sequence */
1118
	init_sequence(relid, &elm, &seqrel);
1119

1120 1121
	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
		pg_class_aclcheck(elm->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
1122 1123
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1124
				 errmsg("permission denied for sequence %s",
1125
						RelationGetRelationName(seqrel))));
1126

1127
	if (elm->increment == 0)	/* nextval/read_info were not called */
1128 1129
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1130
				 errmsg("currval of sequence \"%s\" is not yet defined in this session",
1131
						RelationGetRelationName(seqrel))));
1132 1133 1134

	result = elm->last;

1135 1136
	relation_close(seqrel, NoLock);

1137
	PG_RETURN_INT64(result);
1138 1139
}

1140 1141 1142 1143 1144 1145
Datum
lastval(PG_FUNCTION_ARGS)
{
	Relation	seqrel;
	int64		result;

1146 1147 1148 1149 1150 1151 1152 1153
	/* For now, strictly forbidden on MPP. */
	if (Gp_role == GP_ROLE_DISPATCH || Gp_role == GP_ROLE_EXECUTE)
	{
		ereport(ERROR,
				(errcode(ERRCODE_GP_FEATURE_NOT_SUPPORTED),
				 errmsg("lastval() not supported")));
	}

1154 1155 1156 1157 1158 1159
	if (last_used_seq == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("lastval is not yet defined in this session")));

	/* Someone may have dropped the sequence since the last nextval() */
1160 1161 1162 1163 1164 1165
	if (0 == caql_getcount(
				NULL,
				cql("SELECT COUNT(*) FROM pg_class "
					" WHERE oid = :1 ",
					ObjectIdGetDatum(last_used_seq->relid))))
	{
1166 1167 1168
		ereport(ERROR,
				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
				 errmsg("lastval is not yet defined in this session")));
1169
	}
1170

1171
	seqrel = open_share_lock(last_used_seq);
1172 1173 1174 1175

	/* nextval() must have already been called for this sequence */
	Assert(last_used_seq->increment != 0);

1176 1177
	if (pg_class_aclcheck(last_used_seq->relid, GetUserId(), ACL_SELECT) != ACLCHECK_OK &&
		pg_class_aclcheck(last_used_seq->relid, GetUserId(), ACL_USAGE) != ACLCHECK_OK)
1178 1179 1180 1181 1182 1183 1184
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied for sequence %s",
						RelationGetRelationName(seqrel))));

	result = last_used_seq->last;
	relation_close(seqrel, NoLock);
1185

1186 1187 1188
	PG_RETURN_INT64(result);
}

B
Bruce Momjian 已提交
1189
/*
1190 1191 1192 1193
 * 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 已提交
1194
 * work if multiple users are attached to the database and referencing
1195 1196
 * the sequence (unlikely if pg_dump is restoring it).
 *
B
Bruce Momjian 已提交
1197
 * It is necessary to have the 3 arg version so that pg_dump can
1198 1199 1200 1201
 * 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 已提交
1202
static void
1203
do_setval(Oid relid, int64 next, bool iscalled)
M
 
Marc G. Fournier 已提交
1204
{
1205 1206
	MIRROREDLOCK_BUFMGR_DECLARE;

M
 
Marc G. Fournier 已提交
1207
	SeqTable	elm;
1208
	Relation	seqrel;
1209
	Buffer		buf;
1210
	Form_pg_sequence seq;
M
 
Marc G. Fournier 已提交
1211

1212 1213 1214 1215 1216 1217 1218
	if (Gp_role == GP_ROLE_EXECUTE)
	{
		ereport(ERROR,
				(errcode(ERRCODE_GP_FEATURE_NOT_SUPPORTED),
				 errmsg("setval() not supported in this context")));
	}

1219
	/* open and AccessShareLock sequence */
1220
	init_sequence(relid, &elm, &seqrel);
1221 1222

	if (pg_class_aclcheck(elm->relid, GetUserId(), ACL_UPDATE) != ACLCHECK_OK)
1223 1224
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1225
				 errmsg("permission denied for sequence %s",
1226
						RelationGetRelationName(seqrel))));
M
 
Marc G. Fournier 已提交
1227

1228
	/* lock page' buffer and read tuple */
1229 1230 1231 1232 1233 1234
	
	// -------- MirroredLock ----------
	MIRROREDLOCK_BUFMGR_LOCK;
	
	seq = read_info(seqrel, &buf);
	elm->increment = seq->increment_by;
M
 
Marc G. Fournier 已提交
1235

1236
	if ((next < seq->min_value) || (next > seq->max_value))
1237
	{
B
Bruce Momjian 已提交
1238 1239 1240 1241
		char		bufv[100],
					bufm[100],
					bufx[100];

1242 1243 1244
		snprintf(bufv, sizeof(bufv), INT64_FORMAT, next);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, seq->min_value);
		snprintf(bufx, sizeof(bufx), INT64_FORMAT, seq->max_value);
1245 1246
		ereport(ERROR,
				(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
1247
				 errmsg("setval: value %s is out of bounds for sequence \"%s\" (%s..%s)",
1248 1249
						bufv, RelationGetRelationName(seqrel),
						bufm, bufx)));
1250
	}
M
 
Marc G. Fournier 已提交
1251 1252 1253

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

1256 1257 1258 1259
	// Fetch gp_persistent_relation_node information that will be added to XLOG record.
	Assert(seqrel != NULL);
	Sequence_FetchGpRelationNodeForXLog(seqrel);

1260
	START_CRIT_SECTION();
1261

1262 1263
	MarkBufferDirty(buf);

1264 1265
	/* XLOG stuff */
	if (!seqrel->rd_istemp)
V
Vadim B. Mikheev 已提交
1266 1267 1268
	{
		xl_seq_rec	xlrec;
		XLogRecPtr	recptr;
B
Bruce Momjian 已提交
1269
		XLogRecData rdata[2];
1270
		Page		page = BufferGetPage(buf);
V
Vadim B. Mikheev 已提交
1271

1272
		xlrec.node = seqrel->rd_node;
1273 1274 1275
		xlrec.persistentTid = seqrel->rd_segfile0_relationnodeinfo.persistentTid;
		xlrec.persistentSerialNum = seqrel->rd_segfile0_relationnodeinfo.persistentSerialNum;

B
Bruce Momjian 已提交
1276
		rdata[0].data = (char *) &xlrec;
1277
		rdata[0].len = sizeof(xl_seq_rec);
1278
		rdata[0].buffer = InvalidBuffer;
1279 1280
		rdata[0].next = &(rdata[1]);

1281
		/* set values that will be saved in xlog */
1282
		seq->last_value = next;
1283
		seq->is_called = true;
1284
		seq->log_cnt = 0;
1285

B
Bruce Momjian 已提交
1286 1287 1288
		rdata[1].data = (char *) page + ((PageHeader) page)->pd_upper;
		rdata[1].len = ((PageHeader) page)->pd_special -
			((PageHeader) page)->pd_upper;
1289
		rdata[1].buffer = InvalidBuffer;
1290 1291
		rdata[1].next = NULL;

B
Bruce Momjian 已提交
1292
		recptr = XLogInsert(RM_SEQ_ID, XLOG_SEQ_LOG | XLOG_NO_TRAN, rdata);
1293 1294

		PageSetLSN(page, recptr);
1295
		PageSetTLI(page, ThisTimeLineID);
V
Vadim B. Mikheev 已提交
1296
	}
1297

1298 1299
	/* save info in sequence relation */
	seq->last_value = next;		/* last fetched number */
1300
	seq->is_called = iscalled;
1301
	seq->log_cnt = (iscalled) ? 0 : 1;
1302

1303
	END_CRIT_SECTION();
M
 
Marc G. Fournier 已提交
1304

1305
	UnlockReleaseBuffer(buf);
1306

1307 1308 1309
	MIRROREDLOCK_BUFMGR_UNLOCK;
	// -------- MirroredLock ----------

1310
	relation_close(seqrel, NoLock);
1311 1312
}

1313 1314 1315 1316
/*
 * Implement the 2 arg setval procedure.
 * See do_setval for discussion.
 */
1317
Datum
1318
setval_oid(PG_FUNCTION_ARGS)
1319
{
1320
	Oid			relid = PG_GETARG_OID(0);
1321
	int64		next = PG_GETARG_INT64(1);
1322

1323
	do_setval(relid, next, true);
1324

1325
	PG_RETURN_INT64(next);
1326 1327
}

1328 1329 1330 1331
/*
 * Implement the 3 arg setval procedure.
 * See do_setval for discussion.
 */
1332
Datum
1333
setval3_oid(PG_FUNCTION_ARGS)
1334
{
1335
	Oid			relid = PG_GETARG_OID(0);
1336
	int64		next = PG_GETARG_INT64(1);
1337 1338
	bool		iscalled = PG_GETARG_BOOL(2);

1339
	do_setval(relid, next, iscalled);
1340

1341
	PG_RETURN_INT64(next);
M
 
Marc G. Fournier 已提交
1342 1343
}

1344

1345
/*
1346 1347
 * Open the sequence and acquire AccessShareLock if needed
 *
1348
 * If we haven't touched the sequence already in this transaction,
B
Bruce Momjian 已提交
1349
 * we need to acquire AccessShareLock.	We arrange for the lock to
1350 1351 1352
 * be owned by the top transaction, so that we don't need to do it
 * more than once per xact.
 */
1353 1354
static Relation
open_share_lock(SeqTable seq)
1355 1356 1357
{
	TransactionId thisxid = GetTopTransactionId();

1358
	/* Get the lock if not already held in this xact */
1359 1360 1361 1362 1363 1364 1365 1366
	if (seq->xid != thisxid)
	{
		ResourceOwner currentOwner;

		currentOwner = CurrentResourceOwner;
		PG_TRY();
		{
			CurrentResourceOwner = TopTransactionResourceOwner;
1367
			LockRelationOid(seq->relid, AccessShareLock);
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
		}
		PG_CATCH();
		{
			/* Ensure CurrentResourceOwner is restored on error */
			CurrentResourceOwner = currentOwner;
			PG_RE_THROW();
		}
		PG_END_TRY();
		CurrentResourceOwner = currentOwner;

1378
		/* Flag that we have a lock in the current xact */
1379 1380
		seq->xid = thisxid;
	}
1381 1382 1383

	/* We now know we have AccessShareLock, and can safely open the rel */
	return relation_open(seq->relid, NoLock);
1384 1385
}

1386
/*
1387
 * Given a relation OID, open and lock the sequence.  p_elm and p_rel are
1388 1389 1390
 * output parameters.
 */
static void
1391
init_sequence(Oid relid, SeqTable *p_elm, Relation *p_rel)
1392
{
B
Bruce Momjian 已提交
1393
	SeqTable	elm;
1394
	Relation	seqrel;
1395

1396 1397 1398 1399 1400 1401 1402
	/* Look to see if we already have a seqtable entry for relation */
	for (elm = seqtab; elm != NULL; elm = elm->next)
	{
		if (elm->relid == relid)
			break;
	}

1403
	/*
1404
	 * Allocate new seqtable entry if we didn't find one.
1405
	 *
B
Bruce Momjian 已提交
1406 1407 1408
	 * NOTE: seqtable entries remain in the list for the life of a backend. If
	 * the sequence itself is deleted then the entry becomes wasted memory,
	 * but it's small enough that this should not matter.
B
Bruce Momjian 已提交
1409
	 */
1410
	if (elm == NULL)
1411
	{
1412
		/*
B
Bruce Momjian 已提交
1413 1414
		 * Time to make a new seqtable entry.  These entries live as long as
		 * the backend does, so we use plain malloc for them.
1415 1416
		 */
		elm = (SeqTable) malloc(sizeof(SeqTableData));
T
Tom Lane 已提交
1417
		if (elm == NULL)
1418 1419 1420
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
1421
		elm->relid = relid;
1422
		elm->xid = InvalidTransactionId;
1423 1424 1425 1426
		/* increment is set to 0 until we do read_info (see currval) */
		elm->last = elm->cached = elm->increment = 0;
		elm->next = seqtab;
		seqtab = elm;
1427 1428
	}

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
	/*
	 * Open the sequence relation.
	 */
	seqrel = open_share_lock(elm);

	if (seqrel->rd_rel->relkind != RELKIND_SEQUENCE)
		ereport(ERROR,
				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
				 errmsg("\"%s\" is not a sequence",
						RelationGetRelationName(seqrel))));
1439 1440 1441

	*p_elm = elm;
	*p_rel = seqrel;
1442 1443 1444
}


1445 1446
/* Given an opened relation, lock the page buffer and find the tuple */
static Form_pg_sequence
1447
read_info(Relation rel, Buffer *buf)
1448
{
1449 1450 1451 1452 1453
	PageHeader	page;
	ItemId		lp;
	HeapTupleData tuple;
	sequence_magic *sm;
	Form_pg_sequence seq;
1454

1455 1456
	MIRROREDLOCK_BUFMGR_MUST_ALREADY_BE_HELD;

1457 1458 1459 1460 1461 1462 1463
	*buf = ReadBuffer(rel, 0);
	LockBuffer(*buf, BUFFER_LOCK_EXCLUSIVE);

	page = (PageHeader) BufferGetPage(*buf);
	sm = (sequence_magic *) PageGetSpecialPointer(page);

	if (sm->magic != SEQ_MAGIC)
1464 1465
		elog(ERROR, "bad magic number in sequence \"%s\": %08X",
			 RelationGetRelationName(rel), sm->magic);
1466 1467 1468 1469 1470 1471 1472 1473

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

	seq = (Form_pg_sequence) GETSTRUCT(&tuple);

	return seq;
1474 1475
}

1476 1477
/*
 * init_params: process the options list of CREATE or ALTER SEQUENCE,
1478 1479
 * and store the values into appropriate fields of *new.  Also set
 * *owned_by to any OWNED BY option, or to NIL if there is none.
1480 1481 1482 1483
 *
 * If isInit is true, fill any unspecified options with default values;
 * otherwise, do not change existing options that aren't explicitly overridden.
 */
1484
static void
1485 1486
init_params(List *options, bool isInit,
			Form_pg_sequence new, List **owned_by)
1487
{
1488 1489 1490 1491 1492
	DefElem    *last_value = NULL;
	DefElem    *increment_by = NULL;
	DefElem    *max_value = NULL;
	DefElem    *min_value = NULL;
	DefElem    *cache_value = NULL;
1493
	DefElem    *is_cycled = NULL;
1494
	ListCell   *option;
1495

1496 1497
	*owned_by = NIL;

B
Bruce Momjian 已提交
1498
	foreach(option, options)
1499
	{
1500
		DefElem    *defel = (DefElem *) lfirst(option);
1501

1502
		if (strcmp(defel->defname, "increment") == 0)
1503 1504
		{
			if (increment_by)
1505 1506 1507
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1508
			increment_by = defel;
1509
		}
B
Bruce Momjian 已提交
1510

B
Bruce Momjian 已提交
1511
		/*
B
Bruce Momjian 已提交
1512
		 * start is for a new sequence restart is for alter
B
Bruce Momjian 已提交
1513
		 */
1514 1515
		else if (strcmp(defel->defname, "start") == 0 ||
				 strcmp(defel->defname, "restart") == 0)
1516 1517
		{
			if (last_value)
1518 1519 1520
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1521
			last_value = defel;
1522
		}
1523
		else if (strcmp(defel->defname, "maxvalue") == 0)
1524 1525
		{
			if (max_value)
1526 1527 1528
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1529
			max_value = defel;
1530
		}
1531
		else if (strcmp(defel->defname, "minvalue") == 0)
1532 1533
		{
			if (min_value)
1534 1535 1536
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1537
			min_value = defel;
1538
		}
1539
		else if (strcmp(defel->defname, "cache") == 0)
1540 1541
		{
			if (cache_value)
1542 1543 1544
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1545
			cache_value = defel;
1546
		}
1547
		else if (strcmp(defel->defname, "cycle") == 0)
1548
		{
1549
			if (is_cycled)
1550 1551 1552
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1553
			is_cycled = defel;
1554
		}
1555 1556 1557 1558 1559 1560 1561 1562
		else if (strcmp(defel->defname, "owned_by") == 0)
		{
			if (*owned_by)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
			*owned_by = defGetQualifiedName(defel);
		}
1563
		else
1564
			elog(ERROR, "option \"%s\" not recognized",
1565 1566 1567
				 defel->defname);
	}

B
Bruce Momjian 已提交
1568
	/* INCREMENT BY */
1569
	if (increment_by != NULL)
B
Bruce Momjian 已提交
1570 1571
	{
		new->increment_by = defGetInt64(increment_by);
1572 1573 1574
		if (new->increment_by == 0)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1575
					 errmsg("INCREMENT must not be zero")));
B
Bruce Momjian 已提交
1576
	}
1577 1578 1579 1580
	else if (isInit)
		new->increment_by = 1;

	/* CYCLE */
1581
	if (is_cycled != NULL)
1582 1583 1584 1585 1586 1587
	{
		new->is_cycled = intVal(is_cycled->arg);
		Assert(new->is_cycled == false || new->is_cycled == true);
	}
	else if (isInit)
		new->is_cycled = false;
1588

1589
	/* MAXVALUE (null arg means NO MAXVALUE) */
1590
	if (max_value != NULL && max_value->arg)
1591
		new->max_value = defGetInt64(max_value);
1592
	else if (isInit || max_value != NULL)
1593
	{
1594
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1595
			new->max_value = SEQ_MAXVALUE;		/* ascending seq */
1596
		else
B
Bruce Momjian 已提交
1597
			new->max_value = -1;	/* descending seq */
1598
	}
1599

1600
	/* MINVALUE (null arg means NO MINVALUE) */
1601
	if (min_value != NULL && min_value->arg)
1602
		new->min_value = defGetInt64(min_value);
1603
	else if (isInit || min_value != NULL)
1604
	{
1605
		if (new->increment_by > 0)
B
Bruce Momjian 已提交
1606
			new->min_value = 1; /* ascending seq */
1607
		else
B
Bruce Momjian 已提交
1608
			new->min_value = SEQ_MINVALUE;		/* descending seq */
1609
	}
1610

1611
	/* crosscheck min/max */
1612
	if (new->min_value >= new->max_value)
1613
	{
B
Bruce Momjian 已提交
1614 1615 1616
		char		bufm[100],
					bufx[100];

1617 1618
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
		snprintf(bufx, sizeof(bufx), INT64_FORMAT, new->max_value);
1619 1620 1621 1622
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("MINVALUE (%s) must be less than MAXVALUE (%s)",
						bufm, bufx)));
1623
	}
1624

B
Bruce Momjian 已提交
1625
	/* START WITH */
1626
	if (last_value != NULL)
1627
	{
1628
		new->last_value = defGetInt64(last_value);
1629 1630 1631
		new->is_called = false;
		new->log_cnt = 1;
	}
1632
	else if (isInit)
1633
	{
1634 1635 1636 1637
		if (new->increment_by > 0)
			new->last_value = new->min_value;	/* ascending seq */
		else
			new->last_value = new->max_value;	/* descending seq */
1638 1639
		new->is_called = false;
		new->log_cnt = 1;
1640
	}
1641

1642
	/* crosscheck */
1643
	if (new->last_value < new->min_value)
1644
	{
B
Bruce Momjian 已提交
1645 1646 1647
		char		bufs[100],
					bufm[100];

1648 1649
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->min_value);
1650 1651
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1652
				 errmsg("START value (%s) cannot be less than MINVALUE (%s)",
B
Bruce Momjian 已提交
1653
						bufs, bufm)));
1654
	}
1655
	if (new->last_value > new->max_value)
1656
	{
B
Bruce Momjian 已提交
1657 1658 1659
		char		bufs[100],
					bufm[100];

1660 1661
		snprintf(bufs, sizeof(bufs), INT64_FORMAT, new->last_value);
		snprintf(bufm, sizeof(bufm), INT64_FORMAT, new->max_value);
1662 1663
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1664
			   errmsg("START value (%s) cannot be greater than MAXVALUE (%s)",
B
Bruce Momjian 已提交
1665
					  bufs, bufm)));
1666
	}
1667

B
Bruce Momjian 已提交
1668
	/* CACHE */
1669
	if (cache_value != NULL)
1670
	{
1671 1672 1673 1674
		new->cache_value = defGetInt64(cache_value);
		if (new->cache_value <= 0)
		{
			char		buf[100];
B
Bruce Momjian 已提交
1675

1676 1677 1678 1679 1680 1681
			snprintf(buf, sizeof(buf), INT64_FORMAT, new->cache_value);
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("CACHE (%s) must be greater than zero",
							buf)));
		}
1682
	}
1683 1684
	else if (isInit)
		new->cache_value = 1;
1685 1686
}

1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
/*
 * Process an OWNED BY option for CREATE/ALTER SEQUENCE
 *
 * Ownership permissions on the sequence are already checked,
 * but if we are establishing a new owned-by dependency, we must
 * enforce that the referenced table has the same owner and namespace
 * as the sequence.
 */
static void
process_owned_by(Relation seqrel, List *owned_by)
{
	int			nnames;
	Relation	tablerel;
	AttrNumber	attnum;

	nnames = list_length(owned_by);
	Assert(nnames > 0);
	if (nnames == 1)
	{
		/* Must be OWNED BY NONE */
		if (strcmp(strVal(linitial(owned_by)), "none") != 0)
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 errmsg("invalid OWNED BY option"),
B
Bruce Momjian 已提交
1711
				errhint("Specify OWNED BY table.column or OWNED BY NONE.")));
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
		tablerel = NULL;
		attnum = 0;
	}
	else
	{
		List	   *relname;
		char	   *attrname;
		RangeVar   *rel;

		/* Separate relname and attr name */
		relname = list_truncate(list_copy(owned_by), nnames - 1);
		attrname = strVal(lfirst(list_tail(owned_by)));

		/* Open and lock rel to ensure it won't go away meanwhile */
		rel = makeRangeVarFromNameList(relname);
		tablerel = relation_openrv(rel, AccessShareLock);

		/* Must be a regular table */
		if (tablerel->rd_rel->relkind != RELKIND_RELATION)
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("referenced relation \"%s\" is not a table",
							RelationGetRelationName(tablerel))));

		/* We insist on same owner and schema */
		if (seqrel->rd_rel->relowner != tablerel->rd_rel->relowner)
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
P
Peter Eisentraut 已提交
1740
			errmsg("sequence must have same owner as table it is linked to")));
1741 1742 1743
		if (RelationGetNamespace(seqrel) != RelationGetNamespace(tablerel))
			ereport(ERROR,
					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
P
Peter Eisentraut 已提交
1744
					 errmsg("sequence must be in same schema as table it is linked to")));
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755

		/* Now, fetch the attribute number from the system cache */
		attnum = get_attnum(RelationGetRelid(tablerel), attrname);
		if (attnum == InvalidAttrNumber)
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("column \"%s\" of relation \"%s\" does not exist",
							attrname, RelationGetRelationName(tablerel))));
	}

	/*
B
Bruce Momjian 已提交
1756 1757
	 * OK, we are ready to update pg_depend.  First remove any existing AUTO
	 * dependencies for the sequence, then optionally add a new one.
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
	 */
	markSequenceUnowned(RelationGetRelid(seqrel));

	if (tablerel)
	{
		ObjectAddress refobject,
					depobject;

		refobject.classId = RelationRelationId;
		refobject.objectId = RelationGetRelid(tablerel);
		refobject.objectSubId = attnum;
		depobject.classId = RelationRelationId;
		depobject.objectId = RelationGetRelid(seqrel);
		depobject.objectSubId = 0;
		recordDependencyOn(&depobject, &refobject, DEPENDENCY_AUTO);
	}

	/* Done, but hold lock until commit */
	if (tablerel)
		relation_close(tablerel, NoLock);
}

V
Vadim B. Mikheev 已提交
1780

B
Bruce Momjian 已提交
1781
void
1782
seq_redo(XLogRecPtr beginLoc, XLogRecPtr lsn, XLogRecord *record)
V
Vadim B. Mikheev 已提交
1783
{
1784 1785
	MIRROREDLOCK_BUFMGR_DECLARE;

B
Bruce Momjian 已提交
1786 1787 1788 1789 1790 1791 1792
	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);
1793
	sequence_magic *sm;
V
Vadim B. Mikheev 已提交
1794

1795
	if (info != XLOG_SEQ_LOG)
1796
		elog(PANIC, "seq_redo: unknown op code %u", info);
V
Vadim B. Mikheev 已提交
1797

1798
	reln = XLogOpenRelation(xlrec->node);
1799 1800 1801 1802
	
	// -------- MirroredLock ----------
	MIRROREDLOCK_BUFMGR_LOCK;
	
1803 1804
	buffer = XLogReadBuffer(reln, 0, true);
	Assert(BufferIsValid(buffer));
V
Vadim B. Mikheev 已提交
1805 1806
	page = (Page) BufferGetPage(buffer);

1807 1808
	/* Always reinit the page and reinstall the magic number */
	/* See comments in DefineSequence */
1809 1810 1811
	PageInit((Page) page, BufferGetPageSize(buffer), sizeof(sequence_magic));
	sm = (sequence_magic *) PageGetSpecialPointer(page);
	sm->magic = SEQ_MAGIC;
V
Vadim B. Mikheev 已提交
1812

B
Bruce Momjian 已提交
1813
	item = (char *) xlrec + sizeof(xl_seq_rec);
1814 1815
	itemsz = record->xl_len - sizeof(xl_seq_rec);
	itemsz = MAXALIGN(itemsz);
B
Bruce Momjian 已提交
1816
	if (PageAddItem(page, (Item) item, itemsz,
1817
					FirstOffsetNumber, LP_USED) == InvalidOffsetNumber)
1818
		elog(PANIC, "seq_redo: failed to add item to page");
V
Vadim B. Mikheev 已提交
1819 1820

	PageSetLSN(page, lsn);
1821
	PageSetTLI(page, ThisTimeLineID);
1822 1823
	MarkBufferDirty(buffer);
	UnlockReleaseBuffer(buffer);
1824 1825 1826 1827
	
	MIRROREDLOCK_BUFMGR_UNLOCK;
	// -------- MirroredLock ----------
	
V
Vadim B. Mikheev 已提交
1828 1829
}

B
Bruce Momjian 已提交
1830
void
1831
seq_desc(StringInfo buf, XLogRecPtr beginLoc, XLogRecord *record)
V
Vadim B. Mikheev 已提交
1832
{
1833 1834
	uint8		info = record->xl_info & ~XLR_INFO_MASK;
	char		*rec = XLogRecGetData(record);
B
Bruce Momjian 已提交
1835
	xl_seq_rec *xlrec = (xl_seq_rec *) rec;
V
Vadim B. Mikheev 已提交
1836 1837

	if (info == XLOG_SEQ_LOG)
1838
		appendStringInfo(buf, "log: ");
V
Vadim B. Mikheev 已提交
1839 1840
	else
	{
1841
		appendStringInfo(buf, "UNKNOWN");
V
Vadim B. Mikheev 已提交
1842 1843 1844
		return;
	}

1845
	appendStringInfo(buf, "rel %u/%u/%u",
B
Bruce Momjian 已提交
1846
			   xlrec->node.spcNode, xlrec->node.dbNode, xlrec->node.relNode);
V
Vadim B. Mikheev 已提交
1847
}
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949


/*
 * Initialize a pseudo relcache entry with just enough info to call bufmgr.
 */
static void
cdb_sequence_relation_init(Relation seqrel,
                           Oid      tablespaceid,
                           Oid      dbid,
                           Oid      relid,
                           bool     istemp)
{
    /* See RelationBuildDesc in relcache.c */
    memset(seqrel, 0, sizeof(*seqrel));

    seqrel->rd_smgr = NULL;
    seqrel->rd_refcnt = 99;

    seqrel->rd_id = relid;
    seqrel->rd_istemp = istemp;

    /* Must use shared buffer pool so seqserver & QDs can see the data. */
    seqrel->rd_isLocalBuf = false;

	seqrel->rd_rel = (Form_pg_class)palloc0(CLASS_TUPLE_SIZE);
    sprintf(seqrel->rd_rel->relname.data, "pg_class.oid=%d", relid);

    /* as in RelationInitPhysicalAddr... */
    seqrel->rd_node.spcNode = tablespaceid;
    seqrel->rd_node.dbNode = dbid;
    seqrel->rd_node.relNode = relid;
}                               /* cdb_sequence_relation_init */

/*
 * Clean up pseudo relcache entry.
 */
static void
cdb_sequence_relation_term(Relation seqrel)
{
    /* Close the file. */
    RelationCloseSmgr(seqrel);

    if (seqrel->rd_rel)
        pfree(seqrel->rd_rel);
}                               /* cdb_sequence_relation_term */



/*
 * CDB: forward a nextval request from qExec to the sequence server
 */
void
cdb_sequence_nextval_proxy(Relation	seqrel,
                           int64   *plast,
                           int64   *pcached,
                           int64   *pincrement,
                           bool    *poverflow)
{

	sendSequenceRequest(GetSeqServerFD(),
						seqrel,
    					gp_session_id,
    					plast,
    					pcached,
    					pincrement,
    					poverflow);

}                               /* cdb_sequence_server_nextval */


/*
 * CDB: nextval entry point called by sequence server
 */
void
cdb_sequence_nextval_server(Oid    tablespaceid,
                            Oid    dbid,
                            Oid    relid,
                            bool   istemp,
                            int64 *plast,
                            int64 *pcached,
                            int64 *pincrement,
                            bool  *poverflow)
{
    RelationData    fakerel;
	Relation	    seqrel = &fakerel;

    *plast = 0;
    *pcached = 0;
    *pincrement = 0;

    /* Build a pseudo relcache entry with just enough info to call bufmgr. */
    seqrel = &fakerel;
    cdb_sequence_relation_init(seqrel, tablespaceid, dbid, relid, istemp);

    /* CDB TODO: Catch errors. */

    /* Update the sequence object. */
    cdb_sequence_nextval(seqrel, plast, pcached, pincrement, poverflow);

    /* Cleanup. */
    cdb_sequence_relation_term(seqrel);
}                               /* cdb_sequence_server_nextval */