command.c 13.1 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * command.c--
4
 *	  random postgres portal and utility support code
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/commands/Attic/command.c,v 1.29 1998/07/27 19:37:51 vadim Exp $
11 12
 *
 * NOTES
13 14 15 16 17 18 19 20
 *	  The PortalExecutorHeapMemory crap needs to be eliminated
 *	  by designing a better executor / portal processing memory
 *	  interface.
 *
 *	  The PerformAddAttribute() code, like most of the relation
 *	  manipulating code in the commands/ directory, should go
 *	  someplace closer to the lib/catalog code.
 *
21 22
 *-------------------------------------------------------------------------
 */
B
Bruce Momjian 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include "postgres.h"

#include "access/heapam.h"
#include "access/relscan.h"
#include "catalog/indexing.h"
#include "catalog/catalog.h"
#include "catalog/catname.h"
#include "catalog/pg_type.h"
#include "commands/command.h"
#include "executor/execdefs.h"
#include "executor/executor.h"
#include "fmgr.h"
#include "optimizer/prep.h"
#include "utils/acl.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/mcxt.h"
#include "utils/portal.h"
#include "utils/syscache.h"
42 43

/* ----------------
44
 *		PortalExecutorHeapMemory stuff
45
 *
46
 *		This is where the XXXSuperDuperHacky code was. -cim 3/15/90
47 48
 * ----------------
 */
49
MemoryContext PortalExecutorHeapMemory = NULL;
50 51

/* --------------------------------
52
 *		PortalCleanup
53 54 55 56 57
 * --------------------------------
 */
void
PortalCleanup(Portal portal)
{
58
	MemoryContext context;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

	/* ----------------
	 *	sanity checks
	 * ----------------
	 */
	AssertArg(PortalIsValid(portal));
	AssertArg(portal->cleanup == PortalCleanup);

	/* ----------------
	 *	set proper portal-executor context before calling ExecMain.
	 * ----------------
	 */
	context = MemoryContextSwitchTo((MemoryContext) PortalGetHeapMemory(portal));
	PortalExecutorHeapMemory = (MemoryContext)
		PortalGetHeapMemory(portal);

	/* ----------------
	 *	tell the executor to shutdown the query
	 * ----------------
	 */
	ExecutorEnd(PortalGetQueryDesc(portal), PortalGetState(portal));

	/* ----------------
	 *	switch back to previous context
	 * ----------------
	 */
	MemoryContextSwitchTo(context);
	PortalExecutorHeapMemory = (MemoryContext) NULL;
87 88 89
}

/* --------------------------------
90
 *		PerformPortalFetch
91 92 93 94
 * --------------------------------
 */
void
PerformPortalFetch(char *name,
95 96 97 98
				   bool forward,
				   int count,
				   char *tag,
				   CommandDest dest)
99
{
100 101 102 103
	Portal		portal;
	int			feature;
	QueryDesc  *queryDesc;
	MemoryContext context;
104 105 106 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

	/* ----------------
	 *	sanity checks
	 * ----------------
	 */
	if (name == NULL)
	{
		elog(NOTICE, "PerformPortalFetch: blank portal unsupported");
		return;
	}

	/* ----------------
	 *	get the portal from the portal name
	 * ----------------
	 */
	portal = GetPortalByName(name);
	if (!PortalIsValid(portal))
	{
		elog(NOTICE, "PerformPortalFetch: portal \"%s\" not found",
			 name);
		return;
	}

	/* ----------------
	 *	switch into the portal context
	 * ----------------
	 */
	context = MemoryContextSwitchTo((MemoryContext) PortalGetHeapMemory(portal));

	AssertState(context ==
			 (MemoryContext) PortalGetHeapMemory(GetPortalByName(NULL)));

	/* ----------------
	 *	setup "feature" to tell the executor what direction and
	 *	how many tuples to fetch.
	 * ----------------
	 */
	if (forward)
		feature = EXEC_FOR;
	else
		feature = EXEC_BACK;

	/* ----------------
	 *	tell the destination to prepare to recieve some tuples
	 * ----------------
	 */
150
	queryDesc = PortalGetQueryDesc(portal);
151 152

	if (dest == None)			/* MOVE */
153
	{
154 155 156
		QueryDesc  *qdesc = (QueryDesc *) palloc(sizeof(QueryDesc));

		memcpy(qdesc, queryDesc, sizeof(QueryDesc));
157 158 159
		qdesc->dest = dest;
		queryDesc = qdesc;
	}
160

161
	BeginCommand(name,
162
				 queryDesc->operation,
163
				 portal->attinfo,		/* QueryDescGetTypeInfo(queryDesc),
164
										 * */
165 166 167 168 169 170 171 172 173 174 175 176 177 178
				 false,			/* portal fetches don't end up in
								 * relations */
				 false,			/* this is a portal fetch, not a "retrieve
								 * portal" */
				 tag,
				 dest);

	/* ----------------
	 *	execute the portal fetch operation
	 * ----------------
	 */
	PortalExecutorHeapMemory = (MemoryContext)
		PortalGetHeapMemory(portal);

179
	ExecutorRun(queryDesc, PortalGetState(portal), feature, count);
180

181 182 183
	if (dest == None)			/* MOVE */
		pfree(queryDesc);

184 185 186 187 188 189 190 191 192 193 194 195 196
	/* ----------------
	 * Note: the "end-of-command" tag is returned by higher-level
	 *		 utility code
	 *
	 * Return blank portal for now.
	 * Otherwise, this named portal will be cleaned.
	 * Note: portals will only be supported within a BEGIN...END
	 * block in the near future.  Later, someone will fix it to
	 * do what is possible across transaction boundries.
	 * ----------------
	 */
	MemoryContextSwitchTo(
			 (MemoryContext) PortalGetHeapMemory(GetPortalByName(NULL)));
197 198 199
}

/* --------------------------------
200
 *		PerformPortalClose
201 202 203 204 205
 * --------------------------------
 */
void
PerformPortalClose(char *name, CommandDest dest)
{
206
	Portal		portal;
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

	/* ----------------
	 *	sanity checks
	 * ----------------
	 */
	if (name == NULL)
	{
		elog(NOTICE, "PerformPortalClose: blank portal unsupported");
		return;
	}

	/* ----------------
	 *	get the portal from the portal name
	 * ----------------
	 */
	portal = GetPortalByName(name);
	if (!PortalIsValid(portal))
	{
		elog(NOTICE, "PerformPortalClose: portal \"%s\" not found",
			 name);
		return;
	}

	/* ----------------
	 *	Note: PortalCleanup is called as a side-effect
	 * ----------------
	 */
	PortalDestroy(&portal);
235 236 237
}

/* ----------------
238
 *		PerformAddAttribute
239
 *
240
 *		adds an additional attribute to a relation
241
 *
242 243 244 245 246
 *		Adds attribute field(s) to a relation.	Each new attribute
 *		is given attnums in sequential order and is added to the
 *		ATTRIBUTE relation.  If the AMI fails, defunct tuples will
 *		remain in the ATTRIBUTE relation for later vacuuming.
 *		Later, there may be some reserved attribute names???
247
 *
248
 *		(If needed, can instead use elog to handle exceptions.)
249
 *
250 251 252 253 254
 *		Note:
 *				Initial idea of ordering the tuple attributes so that all
 *		the variable length domains occured last was scratched.  Doing
 *		so would not speed access too much (in general) and would create
 *		many complications in formtuple, amgetattr, and addattribute.
255
 *
256 257 258 259 260 261 262 263 264
 *		scan attribute catalog for name conflict (within rel)
 *		scan type catalog for absence of data type (if not arg)
 *		create attnum magically???
 *		create attribute tuple
 *		insert attribute in attribute catalog
 *		modify reldesc
 *		create new relation tuple
 *		insert new relation in relation catalog
 *		delete original relation from relation catalog
265 266 267 268
 * ----------------
 */
void
PerformAddAttribute(char *relationName,
269 270
					char *userName,
					bool inherits,
271
					ColumnDef *colDef)
272
{
273 274 275 276 277
	Relation	relrdesc,
				attrdesc;
	HeapScanDesc attsdesc;
	HeapTuple	reltup;
	HeapTuple	attributeTuple;
278 279
	AttributeTupleForm attribute;
	FormData_pg_attribute attributeD;
280 281 282 283 284
	int			i;
	int			minattnum,
				maxatts;
	HeapTuple	tup;
	ScanKeyData key[2];
285
	ItemPointerData oldTID;
286 287 288
	Relation	idescs[Num_pg_attr_indices];
	Relation	ridescs[Num_pg_class_indices];
	bool		hasindex;
289 290 291 292 293 294 295 296

	/*
	 * permissions checking.  this would normally be done in utility.c,
	 * but this particular routine is recursive.
	 *
	 * normally, only the owner of a class can change its schema.
	 */
	if (IsSystemRelationName(relationName))
297
		elog(ERROR, "PerformAddAttribute: class \"%s\" is a system catalog",
298
			 relationName);
299
#ifndef NO_SECURITY
300
	if (!pg_ownercheck(userName, relationName, RELNAME))
301
		elog(ERROR, "PerformAddAttribute: you do not own class \"%s\"",
302
			 relationName);
303
#endif
304 305 306 307 308

	/*
	 * we can't add a not null attribute
	 */
	if (colDef->is_not_null)
309
		elog(ERROR, "Can't add a NOT NULL attribute to an existing relation");
310
	if (colDef->defval)
311
		elog(ERROR, "ADD ATTRIBUTE: DEFAULT not yet implemented");
312 313 314 315 316 317 318 319 320 321 322 323 324 325

	/*
	 * if the first element in the 'schema' list is a "*" then we are
	 * supposed to add this attribute to all classes that inherit from
	 * 'relationName' (as well as to 'relationName').
	 *
	 * any permissions or problems with duplicate attributes will cause the
	 * whole transaction to abort, which is what we want -- all or
	 * nothing.
	 */
	if (colDef != NULL)
	{
		if (inherits)
		{
326 327 328 329
			Oid			myrelid,
						childrelid;
			List	   *child,
					   *children;
330 331 332 333

			relrdesc = heap_openr(relationName);
			if (!RelationIsValid(relrdesc))
			{
334
				elog(ERROR, "PerformAddAttribute: unknown relation: \"%s\"",
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
					 relationName);
			}
			myrelid = relrdesc->rd_id;
			heap_close(relrdesc);

			/* this routine is actually in the planner */
			children = find_all_inheritors(lconsi(myrelid, NIL), NIL);

			/*
			 * find_all_inheritors does the recursive search of the
			 * inheritance hierarchy, so all we have to do is process all
			 * of the relids in the list that it returns.
			 */
			foreach(child, children)
			{
				childrelid = lfirsti(child);
				if (childrelid == myrelid)
					continue;
				relrdesc = heap_open(childrelid);
				if (!RelationIsValid(relrdesc))
				{
356
					elog(ERROR, "PerformAddAttribute: can't find catalog entry for inheriting class with oid %d",
357 358 359 360 361 362
						 childrelid);
				}
				PerformAddAttribute((relrdesc->rd_rel->relname).data,
									userName, false, colDef);
				heap_close(relrdesc);
			}
363
		}
364 365 366 367 368 369 370
	}

	relrdesc = heap_openr(RelationRelationName);
	reltup = ClassNameIndexScan(relrdesc, relationName);

	if (!PointerIsValid(reltup))
	{
371
		heap_close(relrdesc);
372
		elog(ERROR, "PerformAddAttribute: relation \"%s\" not found",
373
			 relationName);
374
	}
375

376
	/*
377
	 * XXX is the following check sufficient?
378
	 */
379 380
	if (((Form_pg_class) GETSTRUCT(reltup))->relkind == RELKIND_INDEX)
	{
381
		elog(ERROR, "PerformAddAttribute: index relation \"%s\" not changed",
382 383 384 385 386 387 388 389 390 391
			 relationName);
		return;
	}

	minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
	maxatts = minattnum + 1;
	if (maxatts > MaxHeapAttributeNumber)
	{
		pfree(reltup);			/* XXX temp */
		heap_close(relrdesc);	/* XXX temp */
392
		elog(ERROR, "PerformAddAttribute: relations limited to %d attributes",
393 394
			 MaxHeapAttributeNumber);
		return;
395
	}
396 397 398 399 400 401

	attrdesc = heap_openr(AttributeRelationName);

	Assert(attrdesc);
	Assert(RelationGetRelationTupleForm(attrdesc));

402
	/*
403
	 * Open all (if any) pg_attribute indices
404
	 */
405 406 407 408 409 410 411
	hasindex = RelationGetRelationTupleForm(attrdesc)->relhasindex;
	if (hasindex)
		CatalogOpenIndices(Num_pg_attr_indices, Name_pg_attr_indices, idescs);

	ScanKeyEntryInitialize(&key[0],
						   (bits16) NULL,
						   (AttrNumber) Anum_pg_attribute_attrelid,
B
Bruce Momjian 已提交
412
						   (RegProcedure) F_OIDEQ,
413 414 415 416 417
						   (Datum) reltup->t_oid);

	ScanKeyEntryInitialize(&key[1],
						   (bits16) NULL,
						   (AttrNumber) Anum_pg_attribute_attname,
B
Bruce Momjian 已提交
418
						   (RegProcedure) F_NAMEEQ,
419 420 421 422 423 424 425 426 427 428 429 430 431
						   (Datum) NULL);

	attributeD.attrelid = reltup->t_oid;

	attributeTuple = heap_addheader(Natts_pg_attribute,
									sizeof attributeD,
									(char *) &attributeD);

	attribute = (AttributeTupleForm) GETSTRUCT(attributeTuple);

	i = 1 + minattnum;

	{
432 433 434 435
		HeapTuple	typeTuple;
		TypeTupleForm form;
		char	   *p;
		int			attnelems;
436 437 438 439 440

		/*
		 * XXX use syscache here as an optimization
		 */
		key[1].sk_argument = (Datum) colDef->colname;
441
		attsdesc = heap_beginscan(attrdesc, 0, SnapshotNow, 2, key);
442 443 444 445 446 447 448 449 450


		tup = heap_getnext(attsdesc, 0, (Buffer *) NULL);
		if (HeapTupleIsValid(tup))
		{
			pfree(reltup);		/* XXX temp */
			heap_endscan(attsdesc);		/* XXX temp */
			heap_close(attrdesc);		/* XXX temp */
			heap_close(relrdesc);		/* XXX temp */
451
			elog(ERROR, "PerformAddAttribute: attribute \"%s\" already exists in class \"%s\"",
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
				 key[1].sk_argument,
				 relationName);
			return;
		}
		heap_endscan(attsdesc);

		/*
		 * check to see if it is an array attribute.
		 */

		p = colDef->typename->name;

		if (colDef->typename->arrayBounds)
		{
			attnelems = length(colDef->typename->arrayBounds);
			p = makeArrayTypeName(colDef->typename->name);
		}
		else
			attnelems = 0;

		typeTuple = SearchSysCacheTuple(TYPNAME,
										PointerGetDatum(p),
										0, 0, 0);
		form = (TypeTupleForm) GETSTRUCT(typeTuple);

		if (!HeapTupleIsValid(typeTuple))
478
			elog(ERROR, "Add: type \"%s\" nonexistent", p);
479
		namestrcpy(&(attribute->attname), (char *) key[1].sk_argument);
B
Bruce Momjian 已提交
480

481
		attribute->atttypid = typeTuple->t_oid;
482
		attribute->attlen = form->typlen;
B
Bruce Momjian 已提交
483 484
		attributeD.attdisbursion = 0;
		attribute->attcacheoff = -1;
485
		attribute->atttypmod = colDef->typename->typmod;
486 487 488 489 490 491
		attribute->attnum = i;
		attribute->attbyval = form->typbyval;
		attribute->attnelems = attnelems;
		attribute->attisset = (bool) (form->typtype == 'c');
		attribute->attalign = form->typalign;
		attribute->attnotnull = false;
492
		attribute->atthasdef = (colDef->defval != NULL);
493 494 495 496 497 498 499

		heap_insert(attrdesc, attributeTuple);
		if (hasindex)
			CatalogIndexInsert(idescs,
							   Num_pg_attr_indices,
							   attrdesc,
							   attributeTuple);
500
	}
501

502
	if (hasindex)
503 504 505 506 507 508 509 510 511 512 513 514 515 516
		CatalogCloseIndices(Num_pg_attr_indices, idescs);
	heap_close(attrdesc);

	((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
	oldTID = reltup->t_ctid;
	heap_replace(relrdesc, &oldTID, reltup);

	/* keep catalog indices current */
	CatalogOpenIndices(Num_pg_class_indices, Name_pg_class_indices, ridescs);
	CatalogIndexInsert(ridescs, Num_pg_class_indices, relrdesc, reltup);
	CatalogCloseIndices(Num_pg_class_indices, ridescs);

	pfree(reltup);
	heap_close(relrdesc);
517
}