index.c 47.2 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * index.c--
4
 *	  code to create and destroy POSTGRES index relations
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/catalog/index.c,v 1.31 1997/11/28 04:39:38 momjian Exp $
11 12 13
 *
 *
 * INTERFACE ROUTINES
14 15
 *		index_create()			- Create a cataloged index relation
 *		index_destroy()			- Removes index relation from catalogs
16 17
 *
 * NOTES
18 19 20 21 22
 *	  Much of this code uses hardcoded sequential heap relation scans
 *	  to fetch information from the catalogs.  These should all be
 *	  rewritten to use the system caches lookup routines like
 *	  SearchSysCacheTuple, which can do efficient lookup and
 *	  caching.
23 24 25
 *
 *-------------------------------------------------------------------------
 */
26
#include <postgres.h>
27

28 29 30
#include <catalog/pg_proc.h>
#include <storage/bufmgr.h>
#include <fmgr.h>
31 32
#include <access/genam.h>
#include <access/heapam.h>
33
#include <access/istrat.h>
34 35 36 37 38 39 40
#include <access/xact.h>
#include <bootstrap/bootstrap.h>
#include <catalog/catname.h>
#include <catalog/catalog.h>
#include <catalog/indexing.h>
#include <catalog/heap.h>
#include <catalog/index.h>
41
#include <catalog/pg_type.h>
42
#include <executor/executor.h>
43
#include <miscadmin.h>
44 45
#include <optimizer/clauses.h>
#include <optimizer/prep.h>
46 47 48 49 50 51 52 53
#include <parser/parse_func.h>
#include <storage/lmgr.h>
#include <storage/smgr.h>
#include <utils/builtins.h>
#include <utils/mcxt.h>
#include <utils/relcache.h>
#include <utils/syscache.h>
#include <utils/tqual.h>
54 55

#ifndef HAVE_MEMMOVE
56
#include <regex/utils.h>
57
#else
58
#include <string.h>
59
#endif
60 61 62 63 64 65 66 67

/*
 * macros used in guessing how many tuples are on a page.
 */
#define AVG_TUPLE_SIZE 8
#define NTUPLES_PER_PAGE(natts) (BLCKSZ/((natts)*AVG_TUPLE_SIZE))

/* non-export function prototypes */
68 69 70
static Oid
RelationNameGetObjectId(char *relationName, Relation pg_class,
						bool setHasIndexAttribute);
71
static Oid	GetHeapRelationOid(char *heapRelationName, char *indexRelationName);
72
static TupleDesc BuildFuncTupleDesc(FuncIndexInfo *funcInfo);
73 74
static TupleDesc
ConstructTupleDescriptor(Oid heapoid, Relation heapRelation,
75
						 List *attributeList,
76 77
						 int numatts, AttrNumber attNums[]);

78 79
static void ConstructIndexReldesc(Relation indexRelation, Oid amoid);
static Oid	UpdateRelationRelation(Relation indexRelation);
80 81 82 83 84
static void
InitializeAttributeOids(Relation indexRelation,
						int numatts,
						Oid indexoid);
static void
85
			AppendAttributeTuples(Relation indexRelation, int numatts);
86 87
static void
UpdateIndexRelation(Oid indexoid, Oid heapoid,
88 89 90
					FuncIndexInfo *funcInfo, int natts,
				  AttrNumber attNums[], Oid classOids[], Node *predicate,
					List *attributeList, bool islossy, bool unique);
91
static void
92 93 94
DefaultBuild(Relation heapRelation, Relation indexRelation,
			 int numberOfAttributes, AttrNumber attributeNumber[],
			 IndexStrategy indexStrategy, uint16 parameterCount,
95
	   Datum parameter[], FuncIndexInfoPtr funcInfo, PredInfo *predInfo);
96 97

/* ----------------------------------------------------------------
98 99 100
 *	  sysatts is a structure containing attribute tuple forms
 *	  for system attributes (numbered -1, -2, ...).  This really
 *	  should be generated or eliminated or moved elsewhere. -cim 1/19/91
101 102
 *
 * typedef struct FormData_pg_attribute {
103 104 105 106 107 108 109 110 111 112 113 114 115
 *		Oid				attrelid;
 *		NameData		attname;
 *		Oid				atttypid;
 *		uint32			attnvals;
 *		int16			attlen;
 *		AttrNumber		attnum;
 *		uint32			attnelems;
 *		int32			attcacheoff;
 *		bool			attbyval;
 *		bool			attisset;
 *		char			attalign;
 *		bool			attnotnull;
 *		bool			atthasdef;
116 117 118 119
 * } FormData_pg_attribute;
 *
 * ----------------------------------------------------------------
 */
120 121 122 123
static FormData_pg_attribute sysatts[] = {
	{0l, {"ctid"}, 27l, 0l, 6, -1, 0, -1, '\0', '\0', 'i', '\0', '\0'},
	{0l, {"oid"}, 26l, 0l, 4, -2, 0, -1, '\001', '\0', 'i', '\0', '\0'},
	{0l, {"xmin"}, 28l, 0l, 4, -3, 0, -1, '\0', '\0', 'i', '\0', '\0'},
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
124
	{0l, {"cmin"}, 29l, 0l, 4, -4, 0, -1, '\001', '\0', 'i', '\0', '\0'},
125
	{0l, {"xmax"}, 28l, 0l, 4, -5, 0, -1, '\0', '\0', 'i', '\0', '\0'},
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
126
	{0l, {"cmax"}, 29l, 0l, 4, -6, 0, -1, '\001', '\0', 'i', '\0', '\0'},
127 128 129 130
};

/* ----------------------------------------------------------------
 * RelationNameGetObjectId --
131
 *		Returns the object identifier for a relation given its name.
132 133 134 135 136 137 138 139
 *
 * >	The HASINDEX attribute for the relation with this name will
 * >	be set if it exists and if it is indicated by the call argument.
 * What a load of bull.  This setHasIndexAttribute is totally ignored.
 * This is yet another silly routine to scan the catalogs which should
 * probably be replaced by SearchSysCacheTuple. -cim 1/19/91
 *
 * Note:
140 141
 *		Assumes relation name is valid.
 *		Assumes relation descriptor is valid.
142 143
 * ----------------------------------------------------------------
 */
144
static Oid
145
RelationNameGetObjectId(char *relationName,
146 147 148
						Relation pg_class,
						bool setHasIndexAttribute)
{
149 150 151 152 153
	HeapScanDesc pg_class_scan;
	HeapTuple	pg_class_tuple;
	Oid			relationObjectId;
	Buffer		buffer;
	ScanKeyData key;
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

	/*
	 * If this isn't bootstrap time, we can use the system catalogs to
	 * speed this up.
	 */

	if (!IsBootstrapProcessingMode())
	{
		pg_class_tuple = ClassNameIndexScan(pg_class, relationName);
		if (HeapTupleIsValid(pg_class_tuple))
		{
			relationObjectId = pg_class_tuple->t_oid;
			pfree(pg_class_tuple);
		}
		else
			relationObjectId = InvalidOid;

		return (relationObjectId);
	}

	/* ----------------
	 *	Bootstrap time, do this the hard way.
	 *	begin a scan of pg_class for the named relation
	 * ----------------
	 */
	ScanKeyEntryInitialize(&key, 0, Anum_pg_class_relname,
						   NameEqualRegProcedure,
						   PointerGetDatum(relationName));

183
	pg_class_scan = heap_beginscan(pg_class, 0, false, 1, &key);
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

	/* ----------------
	 *	if we find the named relation, fetch its relation id
	 *	(the oid of the tuple we found).
	 * ----------------
	 */
	pg_class_tuple = heap_getnext(pg_class_scan, 0, &buffer);

	if (!HeapTupleIsValid(pg_class_tuple))
	{
		relationObjectId = InvalidOid;
	}
	else
	{
		relationObjectId = pg_class_tuple->t_oid;
		ReleaseBuffer(buffer);
	}

	/* ----------------
	 *	cleanup and return results
	 * ----------------
	 */
	heap_endscan(pg_class_scan);

	return
		relationObjectId;
210 211 212 213
}


/* ----------------------------------------------------------------
214
 *		GetHeapRelationOid
215 216
 * ----------------------------------------------------------------
 */
217
static Oid
218 219
GetHeapRelationOid(char *heapRelationName, char *indexRelationName)
{
220 221 222
	Relation	pg_class;
	Oid			indoid;
	Oid			heapoid;
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

	/* ----------------
	 *	XXX ADD INDEXING HERE
	 * ----------------
	 */
	/* ----------------
	 *	open pg_class and get the oid of the relation
	 *	corresponding to the name of the index relation.
	 * ----------------
	 */
	pg_class = heap_openr(RelationRelationName);

	indoid = RelationNameGetObjectId(indexRelationName,
									 pg_class,
									 false);

	if (OidIsValid(indoid))
		elog(WARN, "Cannot create index: '%s' already exists",
			 indexRelationName);

	/* ----------------
	 *	get the object id of the heap relation
	 * ----------------
	 */
	heapoid = RelationNameGetObjectId(heapRelationName,
									  pg_class,
									  true);

	/* ----------------
	 *	  check that the heap relation exists..
	 * ----------------
	 */
	if (!OidIsValid(heapoid))
		elog(WARN, "Cannot create index on '%s': relation does not exist",
			 heapRelationName);

	/* ----------------
	 *	  close pg_class and return the heap relation oid
	 * ----------------
	 */
	heap_close(pg_class);

	return heapoid;
266 267
}

268
static TupleDesc
269
BuildFuncTupleDesc(FuncIndexInfo *funcInfo)
270
{
271 272 273 274 275 276
	HeapTuple	tuple;
	TupleDesc	funcTupDesc;
	Oid			retType;
	char	   *funcname;
	int4		nargs;
	Oid		   *argtypes;
277 278 279 280 281 282

	/*
	 * Allocate and zero a tuple descriptor.
	 */
	funcTupDesc = CreateTemplateTupleDesc(1);
	funcTupDesc->attrs[0] = (AttributeTupleForm) palloc(ATTRIBUTE_TUPLE_SIZE);
Bruce Momjian's avatar
Bruce Momjian committed
283
	MemSet(funcTupDesc->attrs[0], 0, ATTRIBUTE_TUPLE_SIZE);
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

	/*
	 * Lookup the function for the return type.
	 */
	funcname = FIgetname(funcInfo);
	nargs = FIgetnArgs(funcInfo);
	argtypes = FIgetArglist(funcInfo);
	tuple = SearchSysCacheTuple(PRONAME,
								PointerGetDatum(funcname),
								Int32GetDatum(nargs),
								PointerGetDatum(argtypes),
								0);

	if (!HeapTupleIsValid(tuple))
		func_error("BuildFuncTupleDesc", funcname, nargs, argtypes);

	retType = ((Form_pg_proc) GETSTRUCT(tuple))->prorettype;

	/*
	 * Look up the return type in pg_type for the type length.
	 */
	tuple = SearchSysCacheTuple(TYPOID,
								ObjectIdGetDatum(retType),
								0, 0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(WARN, "Function %s return type does not exist", FIgetname(funcInfo));

	/*
	 * Assign some of the attributes values. Leave the rest as 0.
	 */
	funcTupDesc->attrs[0]->attlen = ((TypeTupleForm) GETSTRUCT(tuple))->typlen;
	funcTupDesc->attrs[0]->atttypid = retType;
	funcTupDesc->attrs[0]->attnum = 1;
	funcTupDesc->attrs[0]->attbyval = ((TypeTupleForm) GETSTRUCT(tuple))->typbyval;

	/*
	 * make the attributes name the same as the functions
	 */
	namestrcpy(&funcTupDesc->attrs[0]->attname, funcname);

	return (funcTupDesc);
325 326 327
}

/* ----------------------------------------------------------------
328
 *		ConstructTupleDescriptor
329 330
 * ----------------------------------------------------------------
 */
331
static TupleDesc
332
ConstructTupleDescriptor(Oid heapoid,
333
						 Relation heapRelation,
334
						 List *attributeList,
335 336 337
						 int numatts,
						 AttrNumber attNums[])
{
338 339 340 341 342 343 344 345 346 347
	TupleDesc	heapTupDesc;
	TupleDesc	indexTupDesc;
	IndexElem  *IndexKey;
	TypeName   *IndexKeyType;
	AttrNumber	atnum;			/* attributeNumber[attributeOffset] */
	AttrNumber	atind;
	int			natts;			/* RelationTupleForm->relnatts */
	char	   *from;			/* used to simplify memcpy below */
	char	   *to;				/* used to simplify memcpy below */
	int			i;
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

	/* ----------------
	 *	allocate the new tuple descriptor
	 * ----------------
	 */
	natts = RelationGetRelationTupleForm(heapRelation)->relnatts;

	indexTupDesc = CreateTemplateTupleDesc(numatts);

	/* ----------------
	 *
	 * ----------------
	 */

	/* ----------------
	 *	  for each attribute we are indexing, obtain its attribute
	 *	  tuple form from either the static table of system attribute
	 *	  tuple forms or the relation tuple descriptor
	 * ----------------
	 */
	for (i = 0; i < numatts; i += 1)
	{

		/* ----------------
		 *	 get the attribute number and make sure it's valid
		 * ----------------
		 */
		atnum = attNums[i];
		if (atnum > natts)
			elog(WARN, "Cannot create index: attribute %d does not exist",
				 atnum);
		if (attributeList)
		{
			IndexKey = (IndexElem *) lfirst(attributeList);
			attributeList = lnext(attributeList);
			IndexKeyType = IndexKey->tname;
		}
		else
		{
			IndexKeyType = NULL;
		}

		indexTupDesc->attrs[i] = (AttributeTupleForm) palloc(ATTRIBUTE_TUPLE_SIZE);

		/* ----------------
		 *	 determine which tuple descriptor to copy
		 * ----------------
		 */
		if (!AttrNumberIsForUserDefinedAttr(atnum))
		{

			/* ----------------
			 *	  here we are indexing on a system attribute (-1...-12)
			 *	  so we convert atnum into a usable index 0...11 so we can
			 *	  use it to dereference the array sysatts[] which stores
			 *	  tuple descriptor information for system attributes.
			 * ----------------
			 */
			if (atnum <= FirstLowInvalidHeapAttributeNumber || atnum >= 0)
				elog(WARN, "Cannot create index on system attribute: attribute number out of range (%d)", atnum);
			atind = (-atnum) - 1;

			from = (char *) (&sysatts[atind]);

		}
		else
		{
			/* ----------------
			 *	  here we are indexing on a normal attribute (1...n)
			 * ----------------
			 */

			heapTupDesc = RelationGetTupleDescriptor(heapRelation);
			atind = AttrNumberGetAttrOffset(atnum);

			from = (char *) (heapTupDesc->attrs[atind]);
		}

		/* ----------------
		 *	 now that we've determined the "from", let's copy
		 *	 the tuple desc data...
		 * ----------------
		 */

		to = (char *) (indexTupDesc->attrs[i]);
		memcpy(to, from, ATTRIBUTE_TUPLE_SIZE);

		((AttributeTupleForm) to)->attnum = i + 1;
		((AttributeTupleForm) to)->attcacheoff = -1;

		((AttributeTupleForm) to)->attnotnull = false;
		((AttributeTupleForm) to)->atthasdef = false;

		/*
		 * if the keytype is defined, we need to change the tuple form's
		 * atttypid & attlen field to match that of the key's type
		 */
		if (IndexKeyType != NULL)
		{
447
			HeapTuple	tup;
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

			tup = SearchSysCacheTuple(TYPNAME,
									  PointerGetDatum(IndexKeyType->name),
									  0, 0, 0);
			if (!HeapTupleIsValid(tup))
				elog(WARN, "create index: type '%s' undefined",
					 IndexKeyType->name);
			((AttributeTupleForm) to)->atttypid = tup->t_oid;
			((AttributeTupleForm) to)->attbyval =
				((TypeTupleForm) ((char *) tup + tup->t_hoff))->typbyval;
			if (IndexKeyType->typlen > 0)
				((AttributeTupleForm) to)->attlen = IndexKeyType->typlen;
			else
				((AttributeTupleForm) to)->attlen =
					((TypeTupleForm) ((char *) tup + tup->t_hoff))->typlen;
		}


		/* ----------------
		 *	  now we have to drop in the proper relation descriptor
		 *	  into the copied tuple form's attrelid and we should be
		 *	  all set.
		 * ----------------
		 */
		((AttributeTupleForm) to)->attrelid = heapoid;
	}

	return indexTupDesc;
}

/* ----------------------------------------------------------------
 * AccessMethodObjectIdGetAccessMethodTupleForm --
 *		Returns the formated access method tuple given its object identifier.
 *
 * XXX ADD INDEXING
 *
 * Note:
 *		Assumes object identifier is valid.
 * ----------------------------------------------------------------
 */
Form_pg_am
AccessMethodObjectIdGetAccessMethodTupleForm(Oid accessMethodObjectId)
{
491 492 493 494 495
	Relation	pg_am_desc;
	HeapScanDesc pg_am_scan;
	HeapTuple	pg_am_tuple;
	ScanKeyData key;
	Form_pg_am	form;
496 497 498 499 500 501 502 503 504 505 506 507 508 509

	/* ----------------
	 *	form a scan key for the pg_am relation
	 * ----------------
	 */
	ScanKeyEntryInitialize(&key, 0, ObjectIdAttributeNumber,
						   ObjectIdEqualRegProcedure,
						   ObjectIdGetDatum(accessMethodObjectId));

	/* ----------------
	 *	fetch the desired access method tuple
	 * ----------------
	 */
	pg_am_desc = heap_openr(AccessMethodRelationName);
510
	pg_am_scan = heap_beginscan(pg_am_desc, 0, false, 1, &key);
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545

	pg_am_tuple = heap_getnext(pg_am_scan, 0, (Buffer *) NULL);

	/* ----------------
	 *	return NULL if not found
	 * ----------------
	 */
	if (!HeapTupleIsValid(pg_am_tuple))
	{
		heap_endscan(pg_am_scan);
		heap_close(pg_am_desc);
		return (NULL);
	}

	/* ----------------
	 *	if found am tuple, then copy the form and return the copy
	 * ----------------
	 */
	form = (Form_pg_am) palloc(sizeof *form);
	memcpy(form, GETSTRUCT(pg_am_tuple), sizeof *form);

	heap_endscan(pg_am_scan);
	heap_close(pg_am_desc);

	return (form);
}

/* ----------------------------------------------------------------
 *		ConstructIndexReldesc
 * ----------------------------------------------------------------
 */
static void
ConstructIndexReldesc(Relation indexRelation, Oid amoid)
{
	extern GlobalMemory CacheCxt;
546
	MemoryContext oldcxt;
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

	/* ----------------
	 *	  here we make certain to allocate the access method
	 *	  tuple within the cache context lest it vanish when the
	 *	  context changes
	 * ----------------
	 */
	if (!CacheCxt)
		CacheCxt = CreateGlobalMemory("Cache");

	oldcxt = MemoryContextSwitchTo((MemoryContext) CacheCxt);

	indexRelation->rd_am =
		AccessMethodObjectIdGetAccessMethodTupleForm(amoid);

	MemoryContextSwitchTo(oldcxt);

	/* ----------------
	 *	 XXX missing the initialization of some other fields
	 * ----------------
	 */

	indexRelation->rd_rel->relowner = GetUserId();

	indexRelation->rd_rel->relam = amoid;
	indexRelation->rd_rel->reltuples = 1;		/* XXX */
	indexRelation->rd_rel->relkind = RELKIND_INDEX;
}

/* ----------------------------------------------------------------
 *		UpdateRelationRelation
 * ----------------------------------------------------------------
 */
580
static Oid
581 582
UpdateRelationRelation(Relation indexRelation)
{
583 584 585 586
	Relation	pg_class;
	HeapTuple	tuple;
	Oid			tupleOid;
	Relation	idescs[Num_pg_class_indices];
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633

	pg_class = heap_openr(RelationRelationName);

	/* XXX Natts_pg_class_fixed is a hack - see pg_class.h */
	tuple = heap_addheader(Natts_pg_class_fixed,
						   sizeof(*indexRelation->rd_rel),
						   (char *) indexRelation->rd_rel);

	/* ----------------
	 *	the new tuple must have the same oid as the relcache entry for the
	 *	index.	sure would be embarassing to do this sort of thing in polite
	 *	company.
	 * ----------------
	 */
	tuple->t_oid = indexRelation->rd_id;
	heap_insert(pg_class, tuple);

	/*
	 * During normal processing, we need to make sure that the system
	 * catalog indices are correct.  Bootstrap (initdb) time doesn't
	 * require this, because we make sure that the indices are correct
	 * just before exiting.
	 */

	if (!IsBootstrapProcessingMode())
	{
		CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, idescs);
		CatalogIndexInsert(idescs, Num_pg_class_indices, pg_class, tuple);
		CatalogCloseIndices(Num_pg_class_indices, idescs);
	}

	tupleOid = tuple->t_oid;
	pfree(tuple);
	heap_close(pg_class);

	return (tupleOid);
}

/* ----------------------------------------------------------------
 *		InitializeAttributeOids
 * ----------------------------------------------------------------
 */
static void
InitializeAttributeOids(Relation indexRelation,
						int numatts,
						Oid indexoid)
{
634 635
	TupleDesc	tupleDescriptor;
	int			i;
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651

	tupleDescriptor = RelationGetTupleDescriptor(indexRelation);

	for (i = 0; i < numatts; i += 1)
		tupleDescriptor->attrs[i]->attrelid = indexoid;
}

/* ----------------------------------------------------------------
 *		AppendAttributeTuples
 *
 *		XXX For now, only change the ATTNUM attribute value
 * ----------------------------------------------------------------
 */
static void
AppendAttributeTuples(Relation indexRelation, int numatts)
{
652 653 654 655 656
	Relation	pg_attribute;
	HeapTuple	tuple;
	HeapTuple	newtuple;
	bool		hasind;
	Relation	idescs[Num_pg_attr_indices];
657

658 659 660
	Datum		value[Natts_pg_attribute];
	char		nullv[Natts_pg_attribute];
	char		replace[Natts_pg_attribute];
661

662 663
	TupleDesc	indexTupDesc;
	int			i;
664 665 666 667 668 669 670 671 672 673 674 675

	/* ----------------
	 *	open the attribute relation
	 *	XXX ADD INDEXING
	 * ----------------
	 */
	pg_attribute = heap_openr(AttributeRelationName);

	/* ----------------
	 *	initialize null[], replace[] and value[]
	 * ----------------
	 */
Bruce Momjian's avatar
Bruce Momjian committed
676 677
	MemSet(nullv, ' ', Natts_pg_attribute);
	MemSet(replace, ' ', Natts_pg_attribute);
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773

	/* ----------------
	 *	create the first attribute tuple.
	 *	XXX For now, only change the ATTNUM attribute value
	 * ----------------
	 */
	replace[Anum_pg_attribute_attnum - 1] = 'r';
	replace[Anum_pg_attribute_attcacheoff - 1] = 'r';

	value[Anum_pg_attribute_attnum - 1] = Int16GetDatum(1);
	value[Anum_pg_attribute_attcacheoff - 1] = Int32GetDatum(-1);

	tuple = heap_addheader(Natts_pg_attribute,
						   sizeof *(indexRelation->rd_att->attrs[0]),
						   (char *) (indexRelation->rd_att->attrs[0]));

	hasind = false;
	if (!IsBootstrapProcessingMode() && pg_attribute->rd_rel->relhasindex)
	{
		hasind = true;
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);
	}

	/* ----------------
	 *	insert the first attribute tuple.
	 * ----------------
	 */
	tuple = heap_modifytuple(tuple,
							 InvalidBuffer,
							 pg_attribute,
							 value,
							 nullv,
							 replace);

	heap_insert(pg_attribute, tuple);
	if (hasind)
		CatalogIndexInsert(idescs, Num_pg_attr_indices, pg_attribute, tuple);

	/* ----------------
	 *	now we use the information in the index tuple
	 *	descriptor to form the remaining attribute tuples.
	 * ----------------
	 */
	indexTupDesc = RelationGetTupleDescriptor(indexRelation);

	for (i = 1; i < numatts; i += 1)
	{
		/* ----------------
		 *	process the remaining attributes...
		 * ----------------
		 */
		memmove(GETSTRUCT(tuple),
				(char *) indexTupDesc->attrs[i],
				sizeof(FormData_pg_attribute));

		value[Anum_pg_attribute_attnum - 1] = Int16GetDatum(i + 1);

		newtuple = heap_modifytuple(tuple,
									InvalidBuffer,
									pg_attribute,
									value,
									nullv,
									replace);

		heap_insert(pg_attribute, newtuple);
		if (hasind)
			CatalogIndexInsert(idescs, Num_pg_attr_indices, pg_attribute, newtuple);

		/* ----------------
		 *	ModifyHeapTuple returns a new copy of a tuple
		 *	so we free the original and use the copy..
		 * ----------------
		 */
		pfree(tuple);
		tuple = newtuple;
	}

	/* ----------------
	 *	close the attribute relation and free the tuple
	 * ----------------
	 */
	heap_close(pg_attribute);

	if (hasind)
		CatalogCloseIndices(Num_pg_attr_indices, idescs);

	pfree(tuple);
}

/* ----------------------------------------------------------------
 *		UpdateIndexRelation
 * ----------------------------------------------------------------
 */
static void
UpdateIndexRelation(Oid indexoid,
					Oid heapoid,
774
					FuncIndexInfo *funcInfo,
775 776 777
					int natts,
					AttrNumber attNums[],
					Oid classOids[],
778 779
					Node *predicate,
					List *attributeList,
780 781 782
					bool islossy,
					bool unique)
{
783 784 785 786 787 788 789 790 791
	IndexTupleForm indexForm;
	IndexElem  *IndexKey;
	char	   *predString;
	text	   *predText;
	int			predLen,
				itupLen;
	Relation	pg_index;
	HeapTuple	tuple;
	int			i;
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836

	/* ----------------
	 *	allocate an IndexTupleForm big enough to hold the
	 *	index-predicate (if any) in string form
	 * ----------------
	 */
	if (predicate != NULL)
	{
		predString = nodeToString(predicate);
		predText = (text *) fmgr(F_TEXTIN, predString);
		pfree(predString);
	}
	else
	{
		predText = (text *) fmgr(F_TEXTIN, "");
	}
	predLen = VARSIZE(predText);
	itupLen = predLen + sizeof(FormData_pg_index);
	indexForm = (IndexTupleForm) palloc(itupLen);

	memmove((char *) &indexForm->indpred, (char *) predText, predLen);

	/* ----------------
	 *	store the oid information into the index tuple form
	 * ----------------
	 */
	indexForm->indrelid = heapoid;
	indexForm->indexrelid = indexoid;
	indexForm->indproc = (PointerIsValid(funcInfo)) ?
		FIgetProcOid(funcInfo) : InvalidOid;
	indexForm->indislossy = islossy;
	indexForm->indisunique = unique;

	indexForm->indhaskeytype = 0;
	while (attributeList != NIL)
	{
		IndexKey = (IndexElem *) lfirst(attributeList);
		if (IndexKey->tname != NULL)
		{
			indexForm->indhaskeytype = 1;
			break;
		}
		attributeList = lnext(attributeList);
	}

Bruce Momjian's avatar
Bruce Momjian committed
837 838
	MemSet((char *) &indexForm->indkey[0], 0, sizeof indexForm->indkey);
	MemSet((char *) &indexForm->indclass[0], 0, sizeof indexForm->indclass);
839 840 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 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896

	/* ----------------
	 *	copy index key and op class information
	 * ----------------
	 */
	for (i = 0; i < natts; i += 1)
	{
		indexForm->indkey[i] = attNums[i];
		indexForm->indclass[i] = classOids[i];
	}

	/*
	 * If we have a functional index, add all attribute arguments
	 */
	if (PointerIsValid(funcInfo))
	{
		for (i = 1; i < FIgetnArgs(funcInfo); i++)
			indexForm->indkey[i] = attNums[i];
	}

	indexForm->indisclustered = '\0';	/* XXX constant */

	/* ----------------
	 *	open the system catalog index relation
	 * ----------------
	 */
	pg_index = heap_openr(IndexRelationName);

	/* ----------------
	 *	form a tuple to insert into pg_index
	 * ----------------
	 */
	tuple = heap_addheader(Natts_pg_index,
						   itupLen,
						   (char *) indexForm);

	/* ----------------
	 *	insert the tuple into the pg_index
	 *	XXX ADD INDEX TUPLES TOO
	 * ----------------
	 */
	heap_insert(pg_index, tuple);

	/* ----------------
	 *	close the relation and free the tuple
	 * ----------------
	 */
	heap_close(pg_index);
	pfree(predText);
	pfree(indexForm);
	pfree(tuple);
}

/* ----------------------------------------------------------------
 *		UpdateIndexPredicate
 * ----------------------------------------------------------------
 */
void
897
UpdateIndexPredicate(Oid indexoid, Node *oldPred, Node *predicate)
898
{
899 900 901 902 903 904 905 906 907 908 909 910 911
	Node	   *newPred;
	char	   *predString;
	text	   *predText;
	Relation	pg_index;
	HeapTuple	tuple;
	HeapTuple	newtup;
	ScanKeyData entry;
	HeapScanDesc scan;
	Buffer		buffer;
	int			i;
	Datum		values[Natts_pg_index];
	char		nulls[Natts_pg_index];
	char		replace[Natts_pg_index];
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952

	/*
	 * Construct newPred as a CNF expression equivalent to the OR of the
	 * original partial-index predicate ("oldPred") and the extension
	 * predicate ("predicate").
	 *
	 * This should really try to process the result to change things like
	 * "a>2 OR a>1" to simply "a>1", but for now all it does is make sure
	 * that if the extension predicate is NULL (i.e., it is being extended
	 * to be a complete index), then newPred will be NULL - in effect,
	 * changing "a>2 OR TRUE" to "TRUE". --Nels, Jan '93
	 */
	newPred = NULL;
	if (predicate != NULL)
	{
		newPred =
			(Node *) make_orclause(lcons(make_andclause((List *) predicate),
								  lcons(make_andclause((List *) oldPred),
										NIL)));
		newPred = (Node *) cnfify((Expr *) newPred, true);
	}

	/* translate the index-predicate to string form */
	if (newPred != NULL)
	{
		predString = nodeToString(newPred);
		predText = (text *) fmgr(F_TEXTIN, predString);
		pfree(predString);
	}
	else
	{
		predText = (text *) fmgr(F_TEXTIN, "");
	}

	/* open the index system catalog relation */
	pg_index = heap_openr(IndexRelationName);

	ScanKeyEntryInitialize(&entry, 0x0, Anum_pg_index_indexrelid,
						   ObjectIdEqualRegProcedure,
						   ObjectIdGetDatum(indexoid));

953
	scan = heap_beginscan(pg_index, 0, false, 1, &entry);
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
	tuple = heap_getnext(scan, 0, &buffer);
	heap_endscan(scan);

	for (i = 0; i < Natts_pg_index; i++)
	{
		nulls[i] = heap_attisnull(tuple, i + 1) ? 'n' : ' ';
		replace[i] = ' ';
		values[i] = (Datum) NULL;
	}

	replace[Anum_pg_index_indpred - 1] = 'r';
	values[Anum_pg_index_indpred - 1] = (Datum) predText;

	newtup = heap_modifytuple(tuple, buffer, pg_index, values, nulls, replace);

	heap_replace(pg_index, &(newtup->t_ctid), newtup);

	heap_close(pg_index);
	pfree(predText);
}

/* ----------------------------------------------------------------
 *		InitIndexStrategy
 * ----------------------------------------------------------------
 */
void
InitIndexStrategy(int numatts,
				  Relation indexRelation,
				  Oid accessMethodObjectId)
{
984 985 986 987 988 989
	IndexStrategy strategy;
	RegProcedure *support;
	uint16		amstrategies;
	uint16		amsupport;
	Oid			attrelid;
	Size		strsize;
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
	extern GlobalMemory CacheCxt;

	/* ----------------
	 *	get information from the index relation descriptor
	 * ----------------
	 */
	attrelid = indexRelation->rd_att->attrs[0]->attrelid;
	amstrategies = indexRelation->rd_am->amstrategies;
	amsupport = indexRelation->rd_am->amsupport;

	/* ----------------
	 *	get the size of the strategy
	 * ----------------
	 */
	strsize = AttributeNumberGetIndexStrategySize(numatts, amstrategies);

	/* ----------------
	 *	allocate the new index strategy structure
	 *
	 *	the index strategy has to be allocated in the same
	 *	context as the relation descriptor cache or else
	 *	it will be lost at the end of the transaction.
	 * ----------------
	 */
	if (!CacheCxt)
		CacheCxt = CreateGlobalMemory("Cache");

	strategy = (IndexStrategy)
		MemoryContextAlloc((MemoryContext) CacheCxt, strsize);

	if (amsupport > 0)
	{
		strsize = numatts * (amsupport * sizeof(RegProcedure));
		support = (RegProcedure *) MemoryContextAlloc((MemoryContext) CacheCxt,
													  strsize);
	}
	else
	{
		support = (RegProcedure *) NULL;
	}

	/* ----------------
	 *	fill in the index strategy structure with information
	 *	from the catalogs.	Note: we use heap override mode
	 *	in order to be allowed to see the correct information in the
	 *	catalogs, even though our transaction has not yet committed.
	 * ----------------
	 */
	setheapoverride(1);

	IndexSupportInitialize(strategy, support,
						   attrelid, accessMethodObjectId,
						   amstrategies, amsupport, numatts);

	setheapoverride(0);

	/* ----------------
	 *	store the strategy information in the index reldesc
	 * ----------------
	 */
	RelationSetIndexSupport(indexRelation, strategy, support);
}


/* ----------------------------------------------------------------
 *		index_create
 * ----------------------------------------------------------------
 */
void
index_create(char *heapRelationName,
			 char *indexRelationName,
1061 1062
			 FuncIndexInfo *funcInfo,
			 List *attributeList,
1063
			 Oid accessMethodObjectId,
1064
			 int numatts,
1065 1066 1067
			 AttrNumber attNums[],
			 Oid classObjectId[],
			 uint16 parameterCount,
1068 1069
			 Datum *parameter,
			 Node *predicate,
1070 1071
			 bool islossy,
			 bool unique)
1072
{
1073 1074 1075 1076 1077 1078
	Relation	heapRelation;
	Relation	indexRelation;
	TupleDesc	indexTupDesc;
	Oid			heapoid;
	Oid			indexoid;
	PredInfo   *predInfo;
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098

	/* ----------------
	 *	check parameters
	 * ----------------
	 */
	if (numatts < 1)
		elog(WARN, "must index at least one attribute");

	/* ----------------
	 *	  get heap relation oid and open the heap relation
	 *	  XXX ADD INDEXING
	 * ----------------
	 */
	heapoid = GetHeapRelationOid(heapRelationName, indexRelationName);

	heapRelation = heap_open(heapoid);

	/* ----------------
	 * write lock heap to guarantee exclusive access
	 * ----------------
1099 1100 1101
	RelationSetLockForWrite(heapRelation);
	 *                ^^^^^
	 * Does it have any sense ?		- vadim 10/27/97
1102 1103
	 */

1104
	RelationSetLockForRead(heapRelation);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

	/* ----------------
	 *	  construct new tuple descriptor
	 * ----------------
	 */
	if (PointerIsValid(funcInfo))
		indexTupDesc = BuildFuncTupleDesc(funcInfo);
	else
		indexTupDesc = ConstructTupleDescriptor(heapoid,
												heapRelation,
												attributeList,
												numatts,
												attNums);

1119
	/* ----------------
1120
	 *	create the index relation
1121 1122
	 * ----------------
	 */
1123
	indexRelation = heap_create(indexRelationName,
1124 1125
								indexTupDesc);

1126
	/* ----------------
1127 1128 1129
	 *	  construct the index relation descriptor
	 *
	 *	  XXX should have a proper way to create cataloged relations
1130 1131
	 * ----------------
	 */
1132 1133
	ConstructIndexReldesc(indexRelation, accessMethodObjectId);

1134
	/* ----------------
1135 1136
	 *	  add index to catalogs
	 *	  (append RELATION tuple)
1137 1138
	 * ----------------
	 */
1139
	indexoid = UpdateRelationRelation(indexRelation);
1140

1141
	/* ----------------
1142
	 * Now get the index procedure (only relevant for functional indices).
1143 1144 1145
	 * ----------------
	 */

1146 1147
	if (PointerIsValid(funcInfo))
	{
1148
		HeapTuple	proc_tup;
1149

1150 1151 1152 1153 1154
		proc_tup = SearchSysCacheTuple(PRONAME,
									PointerGetDatum(FIgetname(funcInfo)),
									 Int32GetDatum(FIgetnArgs(funcInfo)),
								 PointerGetDatum(FIgetArglist(funcInfo)),
									   0);
1155

1156 1157 1158 1159 1160 1161 1162 1163
		if (!HeapTupleIsValid(proc_tup))
		{
			func_error("index_create", FIgetname(funcInfo),
					   FIgetnArgs(funcInfo),
					   FIgetArglist(funcInfo));
		}
		FIgetProcOid(funcInfo) = proc_tup->t_oid;
	}
1164

1165 1166 1167 1168 1169 1170
	/* ----------------
	 *	now update the object id's of all the attribute
	 *	tuple forms in the index relation's tuple descriptor
	 * ----------------
	 */
	InitializeAttributeOids(indexRelation, numatts, indexoid);
1171 1172

	/* ----------------
1173
	 *	  append ATTRIBUTE tuples
1174 1175
	 * ----------------
	 */
1176 1177
	AppendAttributeTuples(indexRelation, numatts);

1178
	/* ----------------
1179 1180 1181 1182 1183
	 *	  update pg_index
	 *	  (append INDEX tuple)
	 *
	 *	  Note that this stows away a representation of "predicate".
	 *	  (Or, could define a rule to maintain the predicate) --Nels, Feb '92
1184 1185
	 * ----------------
	 */
1186 1187 1188
	UpdateIndexRelation(indexoid, heapoid, funcInfo,
						numatts, attNums, classObjectId, predicate,
						attributeList, islossy, unique);
1189

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
	predInfo = (PredInfo *) palloc(sizeof(PredInfo));
	predInfo->pred = predicate;
	predInfo->oldPred = NULL;

	/* ----------------
	 *	  initialize the index strategy
	 * ----------------
	 */
	InitIndexStrategy(numatts, indexRelation, accessMethodObjectId);

	/*
	 * If this is bootstrap (initdb) time, then we don't actually fill in
	 * the index yet.  We'll be creating more indices and classes later,
	 * so we delay filling them in until just before we're done with
	 * bootstrapping.  Otherwise, we call the routine that constructs the
	 * index.  The heap and index relations are closed by index_build().
	 */
	if (IsBootstrapProcessingMode())
1208
	{
1209 1210 1211 1212
		index_register(heapRelationName, indexRelationName, numatts, attNums,
					   parameterCount, parameter, funcInfo, predInfo);
	}
	else
1213
	{
1214 1215 1216
		heapRelation = heap_openr(heapRelationName);
		index_build(heapRelation, indexRelation, numatts, attNums,
					parameterCount, parameter, funcInfo, predInfo);
1217 1218 1219 1220
	}
}

/* ----------------------------------------------------------------
1221 1222 1223
 *		index_destroy
 *
 *		XXX break into modules like index_create
1224 1225 1226
 * ----------------------------------------------------------------
 */
void
1227
index_destroy(Oid indexId)
1228
{
1229 1230 1231 1232 1233
	Relation	indexRelation;
	Relation	catalogRelation;
	HeapTuple	tuple;
	HeapScanDesc scan;
	ScanKeyData entry;
1234

1235
	Assert(OidIsValid(indexId));
1236

1237
	indexRelation = index_open(indexId);
1238

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
	/* ----------------
	 * fix RELATION relation
	 * ----------------
	 */
	catalogRelation = heap_openr(RelationRelationName);

	ScanKeyEntryInitialize(&entry, 0x0, ObjectIdAttributeNumber,
						   ObjectIdEqualRegProcedure,
						   ObjectIdGetDatum(indexId));;

1249
	scan = heap_beginscan(catalogRelation, 0, false, 1, &entry);
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
	tuple = heap_getnext(scan, 0, (Buffer *) NULL);

	AssertState(HeapTupleIsValid(tuple));

	heap_delete(catalogRelation, &tuple->t_ctid);
	heap_endscan(scan);
	heap_close(catalogRelation);

	/* ----------------
	 * fix ATTRIBUTE relation
	 * ----------------
	 */
	catalogRelation = heap_openr(AttributeRelationName);

	entry.sk_attno = Anum_pg_attribute_attrelid;

1266
	scan = heap_beginscan(catalogRelation, 0, false, 1, &entry);
1267 1268 1269

	while (tuple = heap_getnext(scan, 0, (Buffer *) NULL),
		   HeapTupleIsValid(tuple))
1270
	{
1271 1272

		heap_delete(catalogRelation, &tuple->t_ctid);
1273
	}
1274 1275
	heap_endscan(scan);
	heap_close(catalogRelation);
1276

1277 1278 1279 1280 1281 1282 1283 1284
	/* ----------------
	 * fix INDEX relation
	 * ----------------
	 */
	catalogRelation = heap_openr(IndexRelationName);

	entry.sk_attno = Anum_pg_index_indexrelid;

1285
	scan = heap_beginscan(catalogRelation, 0, false, 1, &entry);
1286 1287 1288 1289 1290 1291
	tuple = heap_getnext(scan, 0, (Buffer *) NULL);
	if (!HeapTupleIsValid(tuple))
	{
		elog(NOTICE, "IndexRelationDestroy: %s's INDEX tuple missing",
			 RelationGetRelationName(indexRelation));
	}
1292
	heap_delete(catalogRelation, &tuple->t_ctid);
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
	heap_endscan(scan);
	heap_close(catalogRelation);

	/*
	 * physically remove the file
	 */
	if (FileNameUnlink(relpath(indexRelation->rd_rel->relname.data)) < 0)
		elog(WARN, "amdestroyr: unlink: %m");

	index_close(indexRelation);
1303 1304 1305
}

/* ----------------------------------------------------------------
1306
 *						index_build support
1307 1308 1309
 * ----------------------------------------------------------------
 */
/* ----------------
1310
 *		FormIndexDatum
1311 1312 1313 1314
 * ----------------
 */
void
FormIndexDatum(int numberOfAttributes,
1315 1316 1317 1318
			   AttrNumber attributeNumber[],
			   HeapTuple heapTuple,
			   TupleDesc heapDescriptor,
			   Buffer buffer,
1319
			   Datum *datum,
1320 1321
			   char *nullv,
			   FuncIndexInfoPtr fInfo)
1322
{
1323 1324 1325
	AttrNumber	i;
	int			offset;
	bool		isNull;
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348

	/* ----------------
	 *	for each attribute we need from the heap tuple,
	 *	get the attribute and stick it into the datum and
	 *	null arrays.
	 * ----------------
	 */

	for (i = 1; i <= numberOfAttributes; i += 1)
	{
		offset = AttrNumberGetAttrOffset(i);

		datum[offset] =
			PointerGetDatum(GetIndexValue(heapTuple,
										  heapDescriptor,
										  offset,
										  attributeNumber,
										  fInfo,
										  &isNull,
										  buffer));

		nullv[offset] = (isNull) ? 'n' : ' ';
	}
1349 1350 1351 1352
}


/* ----------------
1353
 *		UpdateStats
1354 1355 1356 1357 1358
 * ----------------
 */
void
UpdateStats(Oid relid, long reltuples, bool hasindex)
{
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
	Relation	whichRel;
	Relation	pg_class;
	HeapScanDesc pg_class_scan;
	HeapTuple	htup;
	HeapTuple	newtup;
	long		relpages;
	Buffer		buffer;
	int			i;
	Form_pg_class rd_rel;
	Relation	idescs[Num_pg_class_indices];
1369 1370 1371 1372

	static ScanKeyData key[1] = {
		{0, ObjectIdAttributeNumber, ObjectIdEqualRegProcedure}
	};
1373 1374 1375
	Datum		values[Natts_pg_class];
	char		nulls[Natts_pg_class];
	char		replace[Natts_pg_class];
1376

1377
	fmgr_info(ObjectIdEqualRegProcedure, (func_ptr *) &key[0].sk_func,
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
			  &key[0].sk_nargs);

	/* ----------------
	 * This routine handles updates for both the heap and index relation
	 * statistics.	In order to guarantee that we're able to *see* the index
	 * relation tuple, we bump the command counter id here.  The index
	 * relation tuple was created in the current transaction.
	 * ----------------
	 */
	CommandCounterIncrement();

	/* ----------------
	 * CommandCounterIncrement() flushes invalid cache entries, including
	 * those for the heap and index relations for which we're updating
	 * statistics.	Now that the cache is flushed, it's safe to open the
	 * relation again.	We need the relation open in order to figure out
	 * how many blocks it contains.
	 * ----------------
	 */

	whichRel = RelationIdGetRelation(relid);

	if (!RelationIsValid(whichRel))
		elog(WARN, "UpdateStats: cannot open relation id %d", relid);

	/* ----------------
	 * Find the RELATION relation tuple for the given relation.
	 * ----------------
	 */
	pg_class = heap_openr(RelationRelationName);
	if (!RelationIsValid(pg_class))
	{
		elog(WARN, "UpdateStats: could not open RELATION relation");
	}
	key[0].sk_argument = ObjectIdGetDatum(relid);

	pg_class_scan =
1415
		heap_beginscan(pg_class, 0, false, 1, key);
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449

	if (!HeapScanIsValid(pg_class_scan))
	{
		heap_close(pg_class);
		elog(WARN, "UpdateStats: cannot scan RELATION relation");
	}

	/* if the heap_open above succeeded, then so will this heap_getnext() */
	htup = heap_getnext(pg_class_scan, 0, &buffer);
	heap_endscan(pg_class_scan);

	/* ----------------
	 *	update statistics
	 * ----------------
	 */
	relpages = RelationGetNumberOfBlocks(whichRel);

	/*
	 * We shouldn't have to do this, but we do...  Modify the reldesc in
	 * place with the new values so that the cache contains the latest
	 * copy.
	 */

	whichRel->rd_rel->relhasindex = hasindex;
	whichRel->rd_rel->relpages = relpages;
	whichRel->rd_rel->reltuples = reltuples;

	for (i = 0; i < Natts_pg_class; i++)
	{
		nulls[i] = heap_attisnull(htup, i + 1) ? 'n' : ' ';
		replace[i] = ' ';
		values[i] = (Datum) NULL;
	}

1450
	/*
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
	 * If reltuples wasn't supplied take an educated guess.
	 */
	if (reltuples == 0)
		reltuples = relpages * NTUPLES_PER_PAGE(whichRel->rd_rel->relnatts);

	if (IsBootstrapProcessingMode())
	{

		/*
		 * At bootstrap time, we don't need to worry about concurrency or
		 * visibility of changes, so we cheat.
		 */

		rd_rel = (Form_pg_class) GETSTRUCT(htup);
		rd_rel->relpages = relpages;
		rd_rel->reltuples = reltuples;
		rd_rel->relhasindex = hasindex;
	}
	else
	{
		/* during normal processing, work harder */
		replace[Anum_pg_class_relpages - 1] = 'r';
		values[Anum_pg_class_relpages - 1] = (Datum) relpages;
		replace[Anum_pg_class_reltuples - 1] = 'r';
		values[Anum_pg_class_reltuples - 1] = (Datum) reltuples;
		replace[Anum_pg_class_relhasindex - 1] = 'r';
		values[Anum_pg_class_relhasindex - 1] = CharGetDatum(hasindex);

		newtup = heap_modifytuple(htup, buffer, pg_class, values,
								  nulls, replace);
		heap_replace(pg_class, &(newtup->t_ctid), newtup);
		CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, idescs);
		CatalogIndexInsert(idescs, Num_pg_class_indices, pg_class, newtup);
		CatalogCloseIndices(Num_pg_class_indices, idescs);
	}

	heap_close(pg_class);
	heap_close(whichRel);
1489 1490 1491 1492
}


/* -------------------------
1493 1494 1495
 *		FillDummyExprContext
 *			Sets up dummy ExprContext and TupleTableSlot objects for use
 *			with ExecQual.
1496 1497 1498
 * -------------------------
 */
void
1499 1500
FillDummyExprContext(ExprContext *econtext,
					 TupleTableSlot *slot,
1501 1502
					 TupleDesc tupdesc,
					 Buffer buffer)
1503
{
1504 1505 1506 1507 1508 1509 1510 1511 1512
	econtext->ecxt_scantuple = slot;
	econtext->ecxt_innertuple = NULL;
	econtext->ecxt_outertuple = NULL;
	econtext->ecxt_param_list_info = NULL;
	econtext->ecxt_range_table = NULL;

	slot->ttc_tupleDescriptor = tupdesc;
	slot->ttc_buffer = buffer;
	slot->ttc_shouldFree = false;
1513 1514 1515 1516 1517

}


/* ----------------
1518
 *		DefaultBuild
1519 1520 1521 1522
 * ----------------
 */
static void
DefaultBuild(Relation heapRelation,
1523 1524 1525 1526 1527 1528 1529
			 Relation indexRelation,
			 int numberOfAttributes,
			 AttrNumber attributeNumber[],
			 IndexStrategy indexStrategy,		/* not used */
			 uint16 parameterCount,		/* not used */
			 Datum parameter[], /* not used */
			 FuncIndexInfoPtr funcInfo,
1530
			 PredInfo *predInfo)
1531
{
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
	HeapScanDesc scan;
	HeapTuple	heapTuple;
	Buffer		buffer;

	IndexTuple	indexTuple;
	TupleDesc	heapDescriptor;
	TupleDesc	indexDescriptor;
	Datum	   *datum;
	char	   *nullv;
	long		reltuples,
				indtuples;
1543

1544
#ifndef OMIT_PARTIAL_INDEX
1545 1546
	ExprContext *econtext;
	TupleTable	tupleTable;
1547 1548
	TupleTableSlot *slot;

1549
#endif
1550 1551
	Node	   *predicate;
	Node	   *oldPred;
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587

	InsertIndexResult insertResult;

	/* ----------------
	 *	more & better checking is needed
	 * ----------------
	 */
	Assert(OidIsValid(indexRelation->rd_rel->relam));	/* XXX */

	/* ----------------
	 *	get the tuple descriptors from the relations so we know
	 *	how to form the index tuples..
	 * ----------------
	 */
	heapDescriptor = RelationGetTupleDescriptor(heapRelation);
	indexDescriptor = RelationGetTupleDescriptor(indexRelation);

	/* ----------------
	 *	datum and null are arrays in which we collect the index attributes
	 *	when forming a new index tuple.
	 * ----------------
	 */
	datum = (Datum *) palloc(numberOfAttributes * sizeof *datum);
	nullv = (char *) palloc(numberOfAttributes * sizeof *nullv);

	/*
	 * If this is a predicate (partial) index, we will need to evaluate
	 * the predicate using ExecQual, which requires the current tuple to
	 * be in a slot of a TupleTable.  In addition, ExecQual must have an
	 * ExprContext referring to that slot.	Here, we initialize dummy
	 * TupleTable and ExprContext objects for this purpose. --Nels, Feb
	 * '92
	 */

	predicate = predInfo->pred;
	oldPred = predInfo->oldPred;
1588 1589

#ifndef OMIT_PARTIAL_INDEX
1590 1591 1592 1593 1594 1595 1596
	if (predicate != NULL || oldPred != NULL)
	{
		tupleTable = ExecCreateTupleTable(1);
		slot = ExecAllocTableSlot(tupleTable);
		econtext = makeNode(ExprContext);
		FillDummyExprContext(econtext, slot, heapDescriptor, buffer);
	}
Marc G. Fournier's avatar
Marc G. Fournier committed
1597 1598 1599 1600 1601 1602
	else
	{
		econtext = NULL;
		tupleTable = 0;
		slot = NULL;
	}
1603 1604 1605 1606 1607
#endif							/* OMIT_PARTIAL_INDEX */

	/* ----------------
	 *	Ok, begin our scan of the base relation.
	 * ----------------
1608
	 */
1609 1610
	scan = heap_beginscan(heapRelation, /* relation */
						  0,	/* start at end */
1611
						  false, /* seeself */
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
						  0,	/* number of keys */
						  (ScanKey) NULL);		/* scan key */

	reltuples = indtuples = 0;

	/* ----------------
	 *	for each tuple in the base relation, we create an index
	 *	tuple and add it to the index relation.  We keep a running
	 *	count of the number of tuples so that we can update pg_class
	 *	with correct statistics when we're done building the index.
	 * ----------------
	 */
	while (heapTuple = heap_getnext(scan, 0, &buffer),
		   HeapTupleIsValid(heapTuple))
	{

		reltuples++;

		/*
		 * If oldPred != NULL, this is an EXTEND INDEX command, so skip
		 * this tuple if it was already in the existing partial index
		 */
		if (oldPred != NULL)
		{
1636
#ifndef OMIT_PARTIAL_INDEX
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
			/* SetSlotContents(slot, heapTuple); */
			slot->val = heapTuple;
			if (ExecQual((List *) oldPred, econtext) == true)
			{
				indtuples++;
				continue;
			}
#endif							/* OMIT_PARTIAL_INDEX */
		}

		/*
		 * Skip this tuple if it doesn't satisfy the partial-index
		 * predicate
		 */
		if (predicate != NULL)
		{
#ifndef OMIT_PARTIAL_INDEX
			/* SetSlotContents(slot, heapTuple); */
			slot->val = heapTuple;
			if (ExecQual((List *) predicate, econtext) == false)
				continue;
#endif							/* OMIT_PARTIAL_INDEX */
		}

1661
		indtuples++;
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688

		/* ----------------
		 *	FormIndexDatum fills in its datum and null parameters
		 *	with attribute information taken from the given heap tuple.
		 * ----------------
		 */
		FormIndexDatum(numberOfAttributes,		/* num attributes */
					   attributeNumber, /* array of att nums to extract */
					   heapTuple,		/* tuple from base relation */
					   heapDescriptor,	/* heap tuple's descriptor */
					   buffer,	/* buffer used in the scan */
					   datum,	/* return: array of attributes */
					   nullv,	/* return: array of char's */
					   funcInfo);

		indexTuple = index_formtuple(indexDescriptor,
									 datum,
									 nullv);

		indexTuple->t_tid = heapTuple->t_ctid;

		insertResult = index_insert(indexRelation, datum, nullv,
									&(heapTuple->t_ctid), heapRelation);

		if (insertResult)
			pfree(insertResult);
		pfree(indexTuple);
1689
	}
1690 1691 1692 1693 1694

	heap_endscan(scan);

	if (predicate != NULL || oldPred != NULL)
	{
1695
#ifndef OMIT_PARTIAL_INDEX
1696 1697
		ExecDestroyTupleTable(tupleTable, false);
#endif							/* OMIT_PARTIAL_INDEX */
1698
	}
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708

	pfree(nullv);
	pfree(datum);

	/*
	 * Okay, now update the reltuples and relpages statistics for both the
	 * heap relation and the index.  These statistics are used by the
	 * planner to choose a scan type.  They are maintained generally by
	 * the vacuum daemon, but we update them here to make the index useful
	 * as soon as possible.
1709
	 */
1710 1711 1712 1713 1714 1715 1716 1717
	UpdateStats(heapRelation->rd_id, reltuples, true);
	UpdateStats(indexRelation->rd_id, indtuples, false);
	if (oldPred != NULL)
	{
		if (indtuples == reltuples)
			predicate = NULL;
		UpdateIndexPredicate(indexRelation->rd_id, oldPred, predicate);
	}
1718 1719 1720
}

/* ----------------
1721
 *		index_build
1722 1723 1724 1725
 * ----------------
 */
void
index_build(Relation heapRelation,
1726 1727 1728 1729
			Relation indexRelation,
			int numberOfAttributes,
			AttrNumber attributeNumber[],
			uint16 parameterCount,
1730 1731 1732
			Datum *parameter,
			FuncIndexInfo *funcInfo,
			PredInfo *predInfo)
1733
{
1734
	RegProcedure procedure;
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769

	/* ----------------
	 *	sanity checks
	 * ----------------
	 */
	Assert(RelationIsValid(indexRelation));
	Assert(PointerIsValid(indexRelation->rd_am));

	procedure = indexRelation->rd_am->ambuild;

	/* ----------------
	 *	use the access method build procedure if supplied..
	 * ----------------
	 */
	if (RegProcedureIsValid(procedure))
		fmgr(procedure,
			 heapRelation,
			 indexRelation,
			 numberOfAttributes,
			 attributeNumber,
			 RelationGetIndexStrategy(indexRelation),
			 parameterCount,
			 parameter,
			 funcInfo,
			 predInfo);
	else
		DefaultBuild(heapRelation,
					 indexRelation,
					 numberOfAttributes,
					 attributeNumber,
					 RelationGetIndexStrategy(indexRelation),
					 parameterCount,
					 parameter,
					 funcInfo,
					 predInfo);
1770 1771
}

1772 1773 1774 1775 1776 1777 1778
/*
 * IndexIsUnique: given an index's relation OID, see if it
 * is unique using the system cache.
 */
bool
IndexIsUnique(Oid indexId)
{
1779 1780
	HeapTuple	tuple;
	IndexTupleForm index;
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793

	tuple = SearchSysCacheTuple(INDEXRELID,
								ObjectIdGetDatum(indexId),
								0, 0, 0);
	if (!HeapTupleIsValid(tuple))
	{
		elog(WARN, "IndexIsUnique: can't find index id %d",
			 indexId);
	}
	index = (IndexTupleForm) GETSTRUCT(tuple);
	Assert(index->indexrelid == indexId);

	return index->indisunique;
1794
}
1795

1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
/*
 * IndexIsUniqueNoCache: same as above function, but don't use the
 * system cache.  if we are called from btbuild, the transaction
 * that is adding the entry to pg_index has not been committed yet.
 * the system cache functions will do a heap scan, but only with
 * NowTimeQual, not SelfTimeQual, so it won't find tuples added
 * by the current transaction (which is good, because if the transaction
 * is aborted, you don't want the tuples sitting around in the cache).
 * so anyway, we have to do our own scan with SelfTimeQual.
 * this is only called when a new index is created, so it's OK
 * if it's slow.
 */
bool
IndexIsUniqueNoCache(Oid indexId)
{
1811 1812 1813 1814 1815 1816
	Relation	pg_index;
	ScanKeyData skey[1];
	HeapScanDesc scandesc;
	HeapTuple	tuple;
	IndexTupleForm index;
	bool		isunique;
1817 1818 1819 1820 1821 1822 1823 1824

	pg_index = heap_openr(IndexRelationName);

	ScanKeyEntryInitialize(&skey[0], (bits16) 0x0,
						   Anum_pg_index_indexrelid,
						   (RegProcedure) ObjectIdEqualRegProcedure,
						   ObjectIdGetDatum(indexId));

1825
	scandesc = heap_beginscan(pg_index, 0, true, 1, skey);
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839

	tuple = heap_getnext(scandesc, 0, NULL);
	if (!HeapTupleIsValid(tuple))
	{
		elog(WARN, "IndexIsUniqueNoCache: can't find index id %d",
			 indexId);
	}
	index = (IndexTupleForm) GETSTRUCT(tuple);
	Assert(index->indexrelid == indexId);
	isunique = index->indisunique;

	heap_endscan(scandesc);
	heap_close(pg_index);
	return isunique;
1840
}