command.c 13.4 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*-------------------------------------------------------------------------
 *
 * command.c--
 *    random postgres portal and utility support code
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *    $Header: /cvsroot/pgsql/src/backend/commands/Attic/command.c,v 1.11 1997/08/21 01:32:19 vadim Exp $
11 12 13 14 15 16 17 18 19 20 21 22
 *
 * NOTES
 *    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.
 *	
 *-------------------------------------------------------------------------
 */
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <postgres.h>

#include <access/relscan.h>
#include <utils/portal.h>  
#include <commands/command.h>
#include <utils/mcxt.h>
#include <executor/executor.h>
#include <executor/execdefs.h>
#include <catalog/indexing.h>
#include <utils/syscache.h>
#include <catalog/catalog.h>
#include <access/heapam.h>  
#include <utils/array.h>
#include <utils/acl.h>
#include <optimizer/prep.h>
#include <catalog/catname.h>
#include <catalog/pg_proc.h>
#include <catalog/pg_type.h>
#include <utils/builtins.h>
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 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

/* ----------------
 * 	PortalExecutorHeapMemory stuff
 *
 *	This is where the XXXSuperDuperHacky code was. -cim 3/15/90
 * ----------------
 */
MemoryContext PortalExecutorHeapMemory  = NULL;

/* --------------------------------
 * 	PortalCleanup
 * --------------------------------
 */
void
PortalCleanup(Portal portal)
{
    MemoryContext	context;
    
    /* ----------------
     *	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
     * ----------------
     */
85
    MemoryContextSwitchTo(context);
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    PortalExecutorHeapMemory = (MemoryContext) NULL;
}

/* --------------------------------
 * 	PerformPortalFetch
 * --------------------------------
 */
void
PerformPortalFetch(char *name,
		   bool forward,
		   int count,
		   char *tag,
		   CommandDest dest)
{
    Portal		portal;
    int			feature;
    QueryDesc		*queryDesc;
    MemoryContext	context;
    
    /* ----------------
     *	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)) {
120 121
	elog(NOTICE, "PerformPortalFetch: portal \"%s\" not found",
	     name);
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
	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
     * ----------------
     */
    queryDesc = PortalGetQueryDesc(portal);
    BeginCommand(name,
		 queryDesc->operation,
		 portal->attinfo,/* QueryDescGetTypeInfo(queryDesc), */
		 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);
    
    ExecutorRun(queryDesc, PortalGetState(portal), feature, count);
    
    /* ----------------
     * 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.
     * ----------------
     */
177
    MemoryContextSwitchTo(
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
	(MemoryContext)PortalGetHeapMemory(GetPortalByName(NULL)));
}

/* --------------------------------
 * 	PerformPortalClose
 * --------------------------------
 */
void
PerformPortalClose(char *name, CommandDest dest)
{
    Portal	portal;
    
    /* ----------------
     *	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)) {
205 206
	elog(NOTICE, "PerformPortalClose: portal \"%s\" not found",
	     name);
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
	return;
    }
    
    /* ----------------
     *	Note: PortalCleanup is called as a side-effect
     * ----------------
     */
    PortalDestroy(&portal);
}

/* ----------------
 *	PerformAddAttribute
 *
 *	adds an additional attribute to a relation
 *
 *	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???
 *
 *	(If needed, can instead use elog to handle exceptions.)
 *
 *	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.
 *
 *	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
 * ----------------
 */
void
PerformAddAttribute(char *relationName,
		    char *userName,
		    bool inherits,
		    ColumnDef *colDef)
{	
    Relation		relrdesc, attrdesc;
    HeapScanDesc	attsdesc;
    HeapTuple		reltup;
    HeapTuple		attributeTuple;
    AttributeTupleForm	attribute;
    FormData_pg_attribute attributeD;
    int			i;
    int			minattnum, maxatts;
    HeapTuple		tup;
    ScanKeyData		key[2];
    ItemPointerData	oldTID;
    Relation		idescs[Num_pg_attr_indices];
    Relation		ridescs[Num_pg_class_indices];
    bool		hasindex;
    
    /*
     * 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))
275 276
	elog(WARN, "PerformAddAttribute: class \"%s\" is a system catalog",
	     relationName);
277 278 279 280 281
#ifndef NO_SECURITY
    if (!pg_ownercheck(userName, relationName, RELNAME))
	elog(WARN, "PerformAddAttribute: you do not own class \"%s\"",
	     relationName);
#endif
282 283 284 285 286
    /*   
     * we can't add a not null attribute
     */
    if (colDef->is_not_null)
        elog(WARN,"Can't add a not null attribute to a existent relation");
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    /*
     * 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) {
	    Oid myrelid, childrelid;
	    List *child, *children;
	    
	    relrdesc = heap_openr(relationName);
	    if (!RelationIsValid(relrdesc)) {
303 304
		elog(WARN, "PerformAddAttribute: unknown relation: \"%s\"",
		     relationName);
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 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
	    }
	    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)) {
		    elog(WARN, "PerformAddAttribute: can't find catalog entry for inheriting class with oid %d",
			 childrelid);
		}
		PerformAddAttribute((relrdesc->rd_rel->relname).data,
				    userName, false, colDef);
		heap_close(relrdesc);
	    }
	}
    }
    
    relrdesc = heap_openr(RelationRelationName);
    reltup = ClassNameIndexScan(relrdesc, relationName);
    
    if (!PointerIsValid(reltup)) {
	heap_close(relrdesc);
	elog(WARN, "PerformAddAttribute: relation \"%s\" not found",
	     relationName);
    }
    /*
     * XXX is the following check sufficient?
     */
    if (((Form_pg_class) GETSTRUCT(reltup))->relkind == RELKIND_INDEX) {
	elog(WARN, "PerformAddAttribute: index relation \"%s\" not changed",
	     relationName);
	return;
    }
    
    minattnum = ((Form_pg_class) GETSTRUCT(reltup))->relnatts;
    maxatts = minattnum + 1;
    if (maxatts > MaxHeapAttributeNumber) {
	pfree(reltup);				/* XXX temp */
	heap_close(relrdesc);			/* XXX temp */
	elog(WARN, "PerformAddAttribute: relations limited to %d attributes",
	     MaxHeapAttributeNumber);
	return;
    }
    
    attrdesc = heap_openr(AttributeRelationName);
    
    Assert(attrdesc);
    Assert(RelationGetRelationTupleForm(attrdesc));
    
    /*
     * Open all (if any) pg_attribute indices
     */
    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,
			   (RegProcedure)ObjectIdEqualRegProcedure,
			   (Datum) reltup->t_oid);
    
    ScanKeyEntryInitialize(&key[1],
			   (bits16) NULL,
			   (AttrNumber) Anum_pg_attribute_attname,
                           (RegProcedure)NameEqualRegProcedure,
			   (Datum) NULL);
    
    attributeD.attrelid = reltup->t_oid;
    attributeD.attnvals = 0;		/* XXX temporary */
    attributeD.attcacheoff = -1;
    
    attributeTuple = heap_addheader(Natts_pg_attribute,
				    sizeof attributeD,
				    (char *)&attributeD);
    
    attribute = (AttributeTupleForm)GETSTRUCT(attributeTuple);
    
    i = 1 + minattnum;

    {
	HeapTuple	typeTuple;
	TypeTupleForm	form;
	char *p;
	int attnelems;
	
	/*
	 * XXX use syscache here as an optimization
	 */
	key[1].sk_argument = (Datum)colDef->colname;
 	attsdesc = heap_beginscan(attrdesc, 0, NowTimeQual, 2, key); 


	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 */
	    elog(WARN, "PerformAddAttribute: attribute \"%s\" already exists in class \"%s\"",
		 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)) {
442
	    elog(WARN, "Add: type \"%s\" nonexistent", p);
443 444 445
	}
	namestrcpy(&(attribute->attname), (char*) key[1].sk_argument);
	attribute->atttypid = typeTuple->t_oid;
Bruce Momjian's avatar
Bruce Momjian committed
446
	if (colDef->typename->typlen > 0)
447
	    attribute->attlen = colDef->typename->typlen;
Bruce Momjian's avatar
Bruce Momjian committed
448 449
	else	/* bpchar, varchar, text */
	    attribute->attlen = form->typlen;
450 451 452 453 454 455
	attribute->attnum = i;
	attribute->attbyval = form->typbyval;
	attribute->attnelems = attnelems;
	attribute->attcacheoff = -1;
	attribute->attisset = (bool) (form->typtype == 'c');
	attribute->attalign = form->typalign;
456
        attribute->attnotnull = false;
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
	
	heap_insert(attrdesc, attributeTuple);
	if (hasindex)
	    CatalogIndexInsert(idescs,
			       Num_pg_attr_indices,
			       attrdesc,
			       attributeTuple);
    }

    if (hasindex)
	CatalogCloseIndices(Num_pg_attr_indices, idescs);
    heap_close(attrdesc);
    
    ((Form_pg_class) GETSTRUCT(reltup))->relnatts = maxatts;
    oldTID = reltup->t_ctid;
472
    heap_replace(relrdesc, &oldTID, reltup);
473 474 475 476 477 478 479 480 481
    
    /* 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);
}